TSQL SUM列有和没有在同一程序中的位置

时间:2015-07-16 19:10:19

标签: sql-server sum union

我必须从列中逐步汇总一些数据,按日期分组,然后我需要另一个总和但在同一列上使用WHERE语句。

myTable示例:

item | col1 | insertDate
-------------------------
1    | 10   | 01/01/2015
2    | 30   | 01/01/2015
3    | 20   | 01/01/2015
1    | 50   | 02/01/2015
3    | 20   | 02/01/2015
1    | 10   | 03/01/2015
2    | 30   | 03/01/2015
1    | 20   | 04/01/2015

我需要的结果是:

date       | sum(col1) | sum(col1) where item = 1
01/01/2015 | 60        | 10
02/01/2015 | 70        | 50
03/01/2015 | 40        | 10
04/01/2015 | 20        | 20

我已经完成了这个程序:

select sum(col1) as tot, 0 as totItem, 
    CAST(insertDate AS date) as data
from myTable 
where (CAST(insertDate AS date) >= @start) 
    AND (CAST(insertDate AS date) <= @end)
group by CAST(insertDate AS date)
union
select  0 as tot, sum(col1) as totItem,
    CAST(insertDate AS date) as data
from myTable  
where (item = @item) 
    and (CAST(insertDate AS date) >= @start) 
    AND (CAST(insertDate AS date) <= @end)
group by CAST(insertDate AS date)
order by data

我所拥有的几乎就是我想要的东西,但显然每个SELECT有两行

date       | sum(col1) | sum(col1) where item = 1
01/01/2015 | 60        | 0
01/01/2015 | 0         | 10
02/01/2015 | 70        | 0
02/01/2015 | 0         | 50
etc...

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

使用case语句而不是两个不同的总和,如下所示:

Select InsertDate
    , Sum(Col1) as Sum_allCol1
    , Sum(case when item = 1 then col1 else 0 end) as Sum_item1
from MyTable
group by InsertDate

或者,如果您附加到当前语法,则可以将union替换为join

Select distinct a.Data, a.Tot, b.TotItem1 
from
    (select sum(col1) as tot, 
    CAST(insertDate AS date) as data
    from myTable where (CAST(insertDate AS date) >= @start) AND (CAST(insertDate AS date) <= @end)
    group by CAST(insertDate AS date)
    ) a

LEFT JOIN

    (select sum(col1) as totItem1,
    CAST(insertDate AS date) as data
    from myTable  where (item = @item) and (CAST(insertDate AS date) >= @start) AND (CAST(insertDate AS date) <= @end)
    group by CAST(insertDate AS date)
    ) b
on a.Data = b.Data

答案 1 :(得分:0)

您可以在case函数

中使用sum()语句
SELECT
    SUM(col1) sumall,
    SUM(CASE 
           WHEN item = 1 THEN col1
           ELSE 0
        END) sumitem1
    insertDate
    FROM myTable
GROUP BY insertDate