表结构 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
------解决思路----------------------
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