我有两个问题。
第一个:
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
?
答案 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);
请注意SELECT
和GROUP 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;