Sql server SQL Server数据库的优化查询
我的SQL Server数据库中有下表:Sql server SQL Server数据库的优化查询,sql-server,optimization,Sql Server,Optimization,我的SQL Server数据库中有下表: | ID | Class | CId | PId | 7865 | Add Class for Prop | 1043 | 1 | 82 | Advanced Carpet Spotting Advanced Carpet Spotting | 1043 | 1 | 82 | Ad
| 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
如果distinctCId
具有相应的PId=1
,则
Set CId = 1 Otherwise 0
我想要这样的输出
| CId | Status | Count
| 1042 | 0 | 4
| 1043 | 1 | 2
| 1044 | 0 | 3
我可以通过使用多个查询获得所需的输出,但我希望得到更优化的输出
请提出解决办法。谢谢。如果
PId
总是1
和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
SELECT
CID,
AVG([Status] * 1) AS [Status],
COUNT(*) AS [Count]
FROM
YourTable
GROUP BY
CID
使用
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个值。请检查您的问题:(1)您正在重置CId
的值(不确定这是您的意图),(2)状态从何而来?此外,请介绍您当前的解决方案,并解释其问题所在。