刚接触 SQL,需要快速回答。我今天大部分时间都在寻找,需要一个快速的答案,所以如果这是相当基本的,我深表歉意。我正在寻找一种方法来“汇总”此查询中的列。
SELECT
Count(case when [BatchNumber] < '100' then 1 else 0 end) as A,
Count(case when [BatchNumber] like '22%' then 1 else 0 end) as B,
Count(case when [BatchNumber] like '33%' then 1 else 0 end) as C,
FROM [Database].[dbo].[Transaction]
WHERE [Date] between '2012-01-03' and '2012-01-05'
Group by [Date]
列中的数据类似于:
Date Batchnumber
2012-01-03 1
2012-01-03 2
2012-01-03 3
2012-01-03 4
2012-01-03 2201
2012-01-03 2202
2012-01-03 3301
2012-01-03 3302
2012-01-03 3303
2012-01-05 1
2012-01-05 2
2012-01-05 3
2012-01-05 4
2012-01-05 5
2012-01-05 3301
2012-01-05 3302
2012-01-05 3303
2012-01-05 3304
寻找长行的输出:
Date A B c
2012-01-03 4 2 3
2012-01-05 5 0 4
提前感谢您的帮助。
编辑:因为我没有正确提出我最初的问题,所以将其回滚。提供的信息确实回答了最初的帖子。
最佳答案
我不认为你想要 distinct
, 你需要一个 GROUP BY
:
SELECT Date,
sum(case when [BatchNumber] < '100' then 1 else 0 end) as A,
sum(case when [BatchNumber] like '22%' then 1 else 0 end) as B,
sum(case when [BatchNumber] like '33%' then 1 else 0 end) as C,
FROM [Database].[dbo].[Transaction]
WHERE [Date] between '2012-01-03' and '12-01-05'
GROUP BY Date;
case
表达式返回 0
或 1
, 所以最大的不同值是 2
.
关于SQL 计算列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65675754/