SQL报告如何计算符合特定条件的记录数

时间:2011-04-01 23:39:35

标签: sql oracle pivot aggregate-functions

假设您有一个表格,如:

id   status  date
-----------------------
1    2       today
2    3       today
3    3       yesterday
4    2       yesterday
5    1       yesterday

并且您希望查询计算给定日期的状态为1,2或3的数字或结果,在示例中,所需的结果集将为:

date        status 1   status 2  status 3 
            count      count     count 
------------------------------------------
today       0          1         1
yesterday   1          1         1

有人能指出我正确的方向吗?谢谢。

2 个答案:

答案 0 :(得分:5)

Select Date
    , Sum( Case When Status = 1 Then 1 Else 0 End ) Status1Count
    , Sum( Case When Status = 2 Then 1 Else 0 End ) Status2Count
    , Sum( Case When Status = 3 Then 1 Else 0 End ) Status3Count
From MyTable
Group By Date

答案 1 :(得分:1)

select status, date, count(*)
from Table
group by status, date

结果:

status date      count
  2    today     1
  3    today     1
  3    yesterday 1
  2    yesterday 1
  1    yesterday 1