当前位置: 代码迷 >> Sql Server >> 分组的sql语句
  详细解决方案

分组的sql语句

热度:61   发布时间:2016-04-24 09:43:44.0
求一个分组的sql语句
表结构 tableA
deviceID         statusID
aaa                       1
aaa                        1
aaa                        1
aaa                        2
aaa                        2
aaa                        3
aaa                        4
bbb                        1
bbb                         1

statusID 分为 1 2 3 4 .....N种
现在想根据不同的statusID, 统计出该种statusID的数量, count(StatusID),  传入参数是@deviceID
想到的结果是
deviceID            count(StatusID)
aaa                     3                   //statusID为1的统计
aaa                     2                   //               为2的统计
aaa                     1
aaa                     1
bbb                      1

这样一个sql语句该怎么写?
------解决思路----------------------
select
   deviceID, [count(StatusID)]
from
(
select
   deviceID,statusID,count(1) as [count(StatusID)]
from
   tableA
where
   deviceID=@deviceID
group by
   deviceID,statusID
) as t

------解决思路----------------------
区分?是这个意思吗
SELECT deviceID,StatusID,COUNT(StatusID)FROM TB
WHERE deviceID=@deviceID GROUP BY deviceID,StatusID


引用:
我照楼上3位写的,结果记录集都不对啊
没有区分StatusID的数据

------解决思路----------------------
with cte as
(
select 'aaa' deviceID, 1 statusID
union all
select 'aaa' deviceID, 1 statusID
union all
select 'aaa' deviceID, 1 statusID
union all
select 'aaa' deviceID, 2 statusID
union all
select 'aaa' deviceID, 2 statusID
union all
select 'aaa' deviceID, 3 statusID
union all
select 'aaa' deviceID, 4 statusID
union all
select 'bbb' deviceID, 1 statusID
union all
select 'bbb' deviceID, 1 statusID
)
select deviceID
,statusID
,COUNT(*) 
from cte
where deviceID = @deviceID
group by 
deviceID
,statusID
order by 
deviceID
  相关解决方案