惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
V
Vulnerabilities – Threatpost
Google Online Security Blog
Google Online Security Blog
Hugging Face - Blog
Hugging Face - Blog
L
LINUX DO - 热门话题
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
D
Docker
C
Cyber Attacks, Cyber Crime and Cyber Security
MyScale Blog
MyScale Blog
P
Palo Alto Networks Blog
T
Tenable Blog
P
Privacy International News Feed
Google DeepMind News
Google DeepMind News
小众软件
小众软件
Cisco Talos Blog
Cisco Talos Blog
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cisco Blogs
T
Threat Research - Cisco Blogs
NISL@THU
NISL@THU
The Hacker News
The Hacker News
Project Zero
Project Zero
AWS News Blog
AWS News Blog
Simon Willison's Weblog
Simon Willison's Weblog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threatpost
V
Visual Studio Blog
The GitHub Blog
The GitHub Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
Jina AI
Jina AI
Cyberwarzone
Cyberwarzone
The Register - Security
The Register - Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
Vercel News
Vercel News
D
Darknet – Hacking Tools, Hacker News & Cyber Security
MongoDB | Blog
MongoDB | Blog
U
Unit 42
Scott Helme
Scott Helme
A
About on SuperTechFans
WordPress大学
WordPress大学
F
Fortinet All Blogs
大猫的无限游戏
大猫的无限游戏
G
GRAHAM CLULEY
Latest news
Latest news
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Schneier on Security

博客园 - 我家的木子

asp-for tag helper失效 EF code first:列名 'Discriminator' 无效 jQuery获取属性 SVN提交修改时出现:Checksum mismatch bat笔记 SEO笔记:构建URL的15个SEO最佳实践 SEO笔记:Anatomy of a URL 妙用Excel数据透视表和透视图向导,将二维数据转换为一维数据 安装WIN7时提示“缺少所需的CD/DVD驱动器设备驱动程序” Xcel 测试版使用手册 Office2003与Office2007默认打开方式的切换 - 我家的木子 - 博客园 对 Office VBA 项目的编程访问被拒绝 SharePoint 2007:该表单无法显示,因为会话状态不可用。 - 我家的木子 - 博客园 将数据库查询结果导出为Excel css滤镜实现页面灰色黑白色效果代码 div最低高度设置 - 我家的木子 - 博客园 Ajax联动之后 js 跨行文本出现“未结束的字符串常量”问题,如何解决 - 我家的木子 - 博客园 回发或者回调参数无效 - 我家的木子 - 博客园
YTD易出现断层问题,请注意!
我家的木子 · 2015-03-15 · via 博客园 - 我家的木子
 1 declare @table table(
 2 company_id int ,--公司编号
 3 quarter_num char(2),--季度
 4 disti varchar(50),--分销商
 5 num int --数量
 6 )
 7 
 8 insert @table
 9 values(1,'Q1','D1',1),(1,'Q1','D1',2)
10 ,(1,'Q3','D2',1)
11 ,(1,'Q4','D1',1)
12 ,(1,'Q2','D1',1)
13 ,(2,'Q1','D1',1)
14 ,(2,'Q3','D1',3)
15 ,(2,'Q4','D1',4)
16 ,(2,'Q2','D1',2)

项目中经常遇到类似YTD(Year to Day,年初1-1至某天的统计)的查询。表结构如上图所示。

而在实际项目中,并不会刚刚好只按照时间这一个参数来分组,比如会增加上图中的disti字段,而此字段最大的特点为,每个公司并不一定都有此分销商的数据

在查询时出现断层的问题,如下图第4行结果所示。

select 
b.company_id,b.quarter_num,b.disti,SUM(a.num) [YTQ]
from @table a join (select distinct company_id,quarter_num,disti from @table )b 
    on a.company_id=b.company_id and a.disti=b.disti and a.quarter_num<=b.quarter_num
group by b.company_id,b.quarter_num,b.disti

正常的需求是公司1,Q3应该有2行数据,D1分销商统计值为4,D2分销商统计值为1;Q4应该增加一条D2统计值为1的记录。

如果偏好于使用YTD查询,请注意在最开始构造基础数据时,囊括所有字段的所有值。