SQL选择计数值负值正值和零值

时间:2013-06-24 10:34:23

标签: sql select count

Select * from Table

Date            Value
2013-06-24      12
2013-06-24      3
2013-06-24     -4
2013-06-24      33
2013-06-25      12
2013-06-25     -2
2013-06-25      43
2013-06-25      1
2013-06-25     -3

现在我将在一个SQL命令中按日期计算所有负值,正值和零值组。

3 个答案:

答案 0 :(得分:3)

SELECT
Date,
SUM(CASE WHEN Value > 0 THEN 1 ELSE 0 END) AS pos,
SUM(CASE WHEN Value < 0 THEN 1 ELSE 0 END) AS neg,
SUM(CASE WHEN Value = 0 THEN 1 ELSE 0 END) AS zero
FROM yourTable
GROUP BY Date

答案 1 :(得分:2)

你可以;

select
    DATE,
    SUM(case when value < 0 then 1 else 0 end) as NEGATIVE,
    SUM(case when value > 0 then 1 else 0 end) as POSITIVE,
    SUM(case when value = 0 then 1 else 0 end) as ZERO
from 
    T
group by date

答案 2 :(得分:2)

select date, count(case when value < 0 then value end) as Negative, 
count(case when value > 0 then value end) as positive
from the_table

希望它有所帮助!