如何使用"结合所有"在SQL?

时间:2018-02-22 11:56:01

标签: sql sql-server

我有两个问题。

第一个

SELECT CreatedOn, COUNT(*) AS locationNonProcessed
FROM Table1
WHERE IsActive = 0
GROUP BY CAST(CreatedOn AS DATE), CreatedOn

第二个

SELECT CreatedOn, COUNT(*) AS locationProcessed
FROM Table1
WHERE IsActive = 1
GROUP BY CAST(CreatedOn AS DATE), CreatedOn

我应该如何对这些查询使用UNION ALL

3 个答案:

答案 0 :(得分:1)

我认为你真的不想union all。实现这一点很简单,结果不是很明智(你不会知道哪个是哪个)。

我怀疑你想要条件聚合:

SELECT CAST(CreatedOn AS DATE),
       SUM(CASE WHEN IsActive = 0 THEN 1 ELSE 0 END) AS locationNonProcessed,
       SUM(CASE WHEN IsActive = 1 THEN 1 ELSE 0 END) as locationProcessed
FROM Table1
GROUP BY CAST(CreatedOn AS DATE);

请注意SELECTGROUP BY

的修正

如果IsActive仅采用0,1和可能NULL的值,则可以简化为:

SELECT CAST(CreatedOn AS DATE),
       SUM(1 - IsActive) AS locationNonProcessed,
       SUM(IsActive) as locationProcessed
FROM Table1
GROUP BY CAST(CreatedOn AS DATE);

答案 1 :(得分:0)

SELECT createdon, IsActive, COUNT(*) AS locationProcessed
FROM Table1
WHERE IsActive in (0, 1)
GROUP BY CAST(CreatedOn AS DATE), CreatedOn, IsActive 

GROUP BY CAST(CreatedOn AS DATE), CreatedOn对我来说很奇怪。这与GROUP BY CreatedOn没有什么不同。

答案 2 :(得分:0)

SELECT createdon,
       SUM(CASE WHEN IsActive = 0 THEN 1 ELSE 0 END) AS locationNonProcessed,
       SUM(CASE WHEN IsActive = 1 THEN 1 ELSE 0 END) as locationProcessed
FROM Table1
GROUP BY CAST(CreatedOn AS DATE), CreatedOn;