TSQL SUM 列在同一过程中有和没有 where

TSQL SUM column with and without where in same procedure

我必须对列中的一些数据求和,按日期分组,然后我需要另一个求和,但在同一列上有一个 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

我所拥有的几乎就是我想要的,但显然我每行都有 2 行 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...

我该如何解决这个问题?

使用 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

您可以在 sum() 函数中使用 case 语句

SELECT
    SUM(col1) sumall,
    SUM(CASE 
           WHEN item = 1 THEN col1
           ELSE 0
        END) sumitem1
    insertDate
    FROM myTable
GROUP BY insertDate