Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server SQL Server数据库的优化查询_Sql Server_Optimization - Fatal编程技术网

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

我的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

如果distinct
CId
具有相应的
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)
状态从何而来?此外,请介绍您当前的解决方案,并解释其问题所在。