SELECT Column_A, SUM(CASE WHEN COLUMN_B = 'x' THEN 1 ELSE 'SET SUM TO 0' END) as total
FROM table
GROUP BY Column_A
ORDER BY Month
有没有办法将sum的值设置为0,我试图找到cloumn_B的最后一个连续x值的总和如果连续中断我需要将总和设置为0
Table
ColumnA Column B Month
A x 1
A x 2
A x 3
A y 4
B x 1
B y 2
B x 3
B x 4
C x 1
C x 2
C y 3
C x 4
The expected result is:
A 0
B 2
C 1
答案 0 :(得分:0)
试试这个
SELECT Column_A, SUM(CASE WHEN COLUMN_B = 'x' THEN 1 ELSE 0 END) as total
FROM table
GROUP BY Column_A
ORDER BY some_date
SUM
不能用于非数字数据类型
如果使用,则会收到错误
操作数数据类型char对sum运算符无效。
SELECT Column_A, ISNULL(CAST(SUM(CASE WHEN COLUMN_B = 'x' THEN 1 END) AS VARCHAR),'SET SUM TO 0') AS total
FROM table
GROUP BY Column_A
ORDER BY some_date
答案 1 :(得分:0)
编辑:
DECLARE @TEMP TABLE (columnA varchar(50), maxMonth int )
INSERT INTO @TEMP (columnA, maxMonth)
SELECT columnA, MAX([Month]) FROM [table]
WHERE columnB != 'x'
GROUP BY columnA
SELECT original.columnA, SUM(CASE when original.[Month] > withMax.maxMonth THEN 1 ELSE 0 END) AS TOTAL
FROM @TEMP withMax JOIN [table] original ON withMax.columnA = original.columnA
WHERE original.columnB = 'x'
GROUP BY original.columnA
此查询应该适合您。