【问题标题】:Optimized query for SQL Server databaseSQL Server 数据库的优化查询
【发布时间】:2016-12-27 16:42:29
【问题描述】:

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

我有多个CIdPId

如果不同的CId有对应的PId = 1那么,

Set CId = 1 Otherwise 0

我想要这样的输出

|  CId | Status | Count  
| 1042 |   0    |   4 
| 1043 |   1    |   2 
| 1044 |   0    |   3   

我可以通过使用多个查询获得所需的输出,但我想要更优化的一个。

请提出解决方案。谢谢。

【问题讨论】:

  • 请检查您的问题:(1)您正在重置CId 的值(不确定这是您的意图),(2)Status 来自哪里?另外,请介绍您当前的解决方案并说明问题所在。

标签: sql-server optimization


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    如果PId 始终为10,您可以执行以下操作。

    SELECT
        CID,
        AVG([Status] * 1) AS [Status],
        COUNT(*) AS [Count]
    FROM
        YourTable
    GROUP BY 
        CID
    

    【讨论】:

      【解决方案3】:

      使用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 值。

      【讨论】:

        猜你喜欢
        • 2015-01-18
        • 2013-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-04
        • 1970-01-01
        • 2013-10-04
        • 1970-01-01
        相关资源
        最近更新 更多