SQL查询组LIKE

时间:2016-04-03 22:41:05

标签: sql

我有一张表,我在其中捕获每个计算错误代码。我有内部(20k故障代码)和外部(60k故障代码)我根据关闭计算故障代码总数

以下是我的数据块:

FaultCode   Count
20001       200
20002       100
60004       300
60034       80

以下代码将为每个FaultCode提供COUNT。

SELECT FaultCode, COUNT(FaultCode) AS COUNT
FROM RmaSummary
WHERE ClosedTime IS NULL AND (FaultCode LIKE '60%' OR FaultCode LIKE '20%') 
GROUP BY FaultCode

但是,我想获得FaultCode LIKE' 60%'或者FaultCodes LIKE' 20%',例如:

FaultCode     COUNT
60k            380
20K            300

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以使用case表达式对值进行分组:

SELECT 
    CASE 
       WHEN FaultCode LIKE '60%' THEN '60K'
       WHEN FaultCode LIKE '20%' THEN '20K'
    END AS FaultCode
    , COUNT(FaultCode) AS COUNT
FROM RmaSummary
WHERE ClosedTime IS NULL AND (FaultCode LIKE '60%' OR FaultCode LIKE '20%') 
GROUP BY 
    CASE 
       WHEN FaultCode LIKE '60%' THEN '60K'
       WHEN FaultCode LIKE '20%' THEN '20K'
    END 

如果您不想重复case表达式,可以将该部分移动到派生表或公用表表达式(如果您的数据库支持该表达式)。