我的SQL Server数据库中有以下表格:
| ID | Class | CId | PId
| 7865 | Add Class for Prop | 1043 | 1
| 82 | Advanced Carpet Spotting Advanced Carpet Spotting | 1043 | 1
| 82 | Advanced Carpet Spotting Advanced Carpet Spotting | 1042 | 1
| 7863 | aTesting | 1042 | 0
| 7218 | aUnique | 1042 | 0
| 85 | Body Mechanics | 1042 | 1
| 88 | Carpet Bonnet Cleaning | 1044 | 0
| 89 | Carpet Shampooing/Extraction | 1044 | 1
| 7829 | Class 10 | 1044 | 0
我有多个CId
和PId
如果不同的CId
有相应的PId = 1
那么,
Set CId = 1 Otherwise 0
我想要这样的输出
| CId | Status | Count
| 1042 | 0 | 4
| 1043 | 1 | 2
| 1044 | 0 | 3
我可以通过使用多个查询获得所需的输出,但我想要更优化的一个。
请提出解决方案。谢谢。
答案 0 :(得分:0)
select cid,
case when count(case when pid = 1 then 1 end) > 0
then 1
else 0
end as status,
count(*) as count
from your_table
group by cid
答案 1 :(得分:0)
如果PId
始终为1
和0
,您可以执行以下操作。
SELECT
CID,
AVG([Status] * 1) AS [Status],
COUNT(*) AS [Count]
FROM
YourTable
GROUP BY
CID
答案 2 :(得分:0)
使用CASE
表达式检查PId的总和是否等于PId的数量。
<强>查询强>
select [CId],
case when sum([Cid]) = count([CId]) then 1
else 0 end as [Status],
count([CId]) as [Count]
from [your_table_name]
group by [CId];
同样PId
应该只有1和0值。