如何在sql server中根据一定的条件选择不同的计数数据

时间:2018-01-23 04:39:03

标签: sql sql-server

我的架构定义为:

表A

+---------+---------+-----------+    
| ITEM_ID | TYPE_ID | DUE_DATE  |
+-------------------------------+
|     15  |      1  | 2018-01-2 |
|     15  |      2  | 2018-01-5 |
|     16  |      1  | 2018-01-2 |
|     16  |      1  | 2018-01-2 |
|     17  |      2  | 2018-01-23|
+-------------------------------+

TYPE ID将始终为1或2。

我想根据类型在今天,一个星期和一个月内发生交易次数。

我想要的输出方案:

|ITEM_ID | COUNT_TODAY_TYPE_1 | COUNT_TODAY_TYPE_2 | COUNT_ONEWEEK_TYPE_1 | COUNT_ONEWEEK_TYPE_1 |

如果没有子类型,我可以通过以下

实现这一点
select typeid,
       sum(case when cast(due_date as date) = cast(getdate() as date) then 1 else 0 end) as today,
       sum(case when cast(due_date as date) >= cast(getdate() - 7 as date) then 1 else 0 end) as week,
       sum(case when cast(due_date as date) >= dateadd(month, -1, cast(getdate() as date)) then 1 else 0 end) as month
from t
group by typeid;

如何获得上述结果?

2 个答案:

答案 0 :(得分:0)

检查这个。

select * from
(
select TYPE_ID, 

       count(case when cast(due_date as date) = cast(getdate() as date) then 1 else NULL end) as COUNT_TODAY_TYPE_1,
       count(case when cast(due_date as date) >= cast(getdate() - 7 as date) then 1 else NULL end) as COUNT_week_TYPE_1,
       count(case when cast(due_date as date) >= dateadd(month, -1, cast(getdate() as date)) then 1 else NULL end) as COUNT_month_TYPE_1
from #A
where TYPE_ID='1'
group by TYPE_ID
)aa,
(
select TYPE_ID, 
       count(case when cast(due_date as date) = cast(getdate() as date) then 1 else NULL end) as COUNT_TODAY_TYPE_2,
       count(case when cast(due_date as date) >= cast(getdate() - 7 as date) then 1 else NULL end) as COUNT_ONEWEEK_TYPE_2,
       count(case when cast(due_date as date) >= dateadd(month, -1, cast(getdate() as date)) then 1 else NULL end) as COUNT_month_TYPE_2
from #A
where TYPE_ID='2'
group by TYPE_ID
)a

使用SELECT COUNT(*)或SELECT COUNT(1)(我更喜欢使用它)将返回结果集中返回的所有记录的总和,而不管NULL值。

答案 1 :(得分:0)

您需要在Sum中添加TypeID,并在

组中使用Iteam ID
select ITEM_ID,
   sum(case when cast(due_date as date) = cast(getdate() as date) and TYPE_ID = 1  then 1 else 0 end) as COUNT_TODAY_TYPE_1,
   sum(case when cast(due_date as date) = cast(getdate() as date) and TYPE_ID = 2  then 1 else 0 end) as COUNT_TODAY_TYPE_2,
   sum(case when cast(due_date as date) >= cast(getdate() - 7 as date)  and TYPE_ID = 1  then 1 else 0 end) as COUNT_ONEWEEK_TYPE_1,
   sum(case when cast(due_date as date) >= cast(getdate() - 7 as date)  and TYPE_ID = 2  then 1 else 0 end) as COUNT_ONEWEEK_TYPE_2,
   sum(case when cast(due_date as date) >= dateadd(month, -1, cast(getdate() as date)) and TYPE_ID = 1   then 1 else 0 end) as COUNT_ONEMONTH_TYPE_1,
   sum(case when cast(due_date as date) >= dateadd(month, -1, cast(getdate() as date)) and TYPE_ID = 2   then 1 else 0 end) as COUNT_ONEMONTH_TYPE_2
from t
group by ITEM_ID;