Sql join和pivot来获取类别总计

时间:2017-12-01 18:41:50

标签: sql-server tsql

我有这些表格。

主要表格

[key]   [CategoryID]
AAAA    100
BBBB    100
CCCC    101
DDDD    102
EEEE    201
FFFF    202
GGGG    202
etc.

类别查询

[CategoryID]    [Category]      [Subcategory]
100             Category1       Subcategory1
101             Category1       Subcategory2
102             Category1       Subcategory3
103             Category1       Subcategory4
200             Category2       SubcategoryA
201             Category2       SubcategoryB
202             Category2       SubcategoryC
etc.

状态查询

[StatusID]  [Description]
0           New
500         Accepted
501         Rejected

状态记录

[key]   [StatusID]      [date]
AAAA    0               2017-01-01
BBBB    0               2017-01-01
CCCC    0               2017-01-01
DDDD    0               2017-01-01
EEEE    0               2017-01-01
FFFF    0               2017-01-01
GGGG    0               2017-01-01
AAAA    500             2017-01-02
BBBB    501             2017-01-02
EEEE    501             2017-01-02
FFFF    500             2017-01-02
BBBB    500             2017-01-03
EEEE    500             2017-01-03
etc.

我想获得每月的结果摘要(通过电子邮件发送)。现在我正在代码中构建汇总表。我想学习如何在SQL中完成它,但我真的不知道从哪里开始。

总表,其总数基于最后[状态历史]值并按[总计] DESC排序。

[Category]  [Subcategory]   [New]   [Accepted]  [Rejected]  [Total]
Category1   Subcategory1    13      8           2           23
Category2   Subcategory3    10      4           6           20
Category1   Subcategory2    5       8           4           17

我试着看看PIVOT这样做,但我不明白如何使用连接以及仅获取最后一个状态历史值。

1 个答案:

答案 0 :(得分:0)

我认为这就是你所追求的。我重新创建了你的数据并对其进行了测试,但我肯定不得不对所涉及的关系做出一两个假设。试试吧,让我知道:

select Category, 
       Subcategory,
       sum(case when description = 'New' then 1 else 0 end) as New,
       sum(case when description = 'Accepted' then 1 else 0 end) as Accepted,
       sum(case when description = 'Rejected' then 1 else 0 end) as Rejected,
       count(*) as Total
from
(select tB.Category, tB.Subcategory, status_lookup.Description
 from status_history inner join (select my_key, max(status_date) as lastdate
                                 from status_history
                                 group by my_key) tA on status_history.my_key = tA.my_key
                                                        and status_history.status_date = tA.lastdate
                    inner join status_lookup on status_history.StatusID = status_lookup.StatusID
                    inner join (select main.my_key, category_lookup.Category, category_lookup.Subcategory
                                from main inner join category_lookup on main.CategoryID = category_lookup.CategoryID) tB on status_history.my_key = tB.my_key) tC
group by Category, Subcategory

我重命名了您的[key]my_key,并分别调用了表maincategory_lookupstatus_lookupstatus_history