我有一个SQL查询,我希望能够计算优先级总数,该优先级的值设置为低,中,高或未指定。
当前最多计数13行,我希望会有多列,例如... 2,4,0
代码:
SELECT c.Name, COUNT(*) as Count_By_Priority,
CASE WHEN cb.Priority = 0 THEN "Unspecified" WHEN cb.Priority = 1 THEN "Low" WHEN cb.Priority = 2 THEN "Medium" WHEN cb.Priority = 3 THEN "High" END as PriorityNumber
FROM TABLE 1 cb
LEFT JOIN Co c ON c.Id = cb.Id
WHERE c.Name LIKE %Name%"
GROUP BY c.Id;
当我期望较低或其他选择时,似乎会为优先级键打印“未指定”。
答案 0 :(得分:1)
我很确定您可以将group by子句更改为c.Id
,然后再PriorityNumber
:
SELECT
c.Name,
COUNT(*) as Count_By_Priority,
CASE
WHEN cb.Priority = 0 THEN "Unspecified"
WHEN cb.Priority = 1 THEN "Low"
WHEN cb.Priority = 2 THEN "Medium"
WHEN cb.Priority = 3 THEN "High"
END as PriorityNumber
FROM TABLE 1 cb
LEFT JOIN Co c
ON c.Id = cb.Id
WHERE c.Name LIKE %Name%"
GROUP BY c.Id, PriorityNumber;
答案 1 :(得分:1)
尝试一下
SELECT c.Name, COUNT(*) as Count_By_Priority,
CASE WHEN cb.Priority = 0 THEN "Unspecified"
WHEN cb.Priority = 1 THEN "Low"
WHEN cb.Priority = 2 THEN "Medium"
WHEN cb.Priority = 3 THEN "High" END as PriorityNumber
FROM TABLE 1 cb LEFT JOIN Co c ON c.Id = cb.Id
WHERE c.Name LIKE %Name%"
GROUP BY c.Name,PriorityNumber ;
答案 2 :(得分:1)
您正在使用聚合,但是您的SELECT
与GROUP BY
不一致。我认为您打算这样做:
SELECT c.Name, COUNT(*) as Count_By_Priority,
(CASE WHEN MAX(cb.Priority) = 0 THEN 'Unspecified'
WHEN MAX(cb.Priority) = 1 THEN 'Low'
WHEN MAX(cb.Priority) = 2 THEN 'Medium'
WHEN MAX(cb.Priority) = 3 THEN 'High'
END) as PriorityNumber
FROM TABLE 1 cb LEFT JOIN
Co c
ON c.Id = cb.Id
WHERE c.Name LIKE '%Name%'
GROUP BY c.Id;
我不确定您是否想要MAX()
或MIN()
,但MAX()
对我来说有意义。
答案 3 :(得分:1)
如果要在单独的列中计算每个优先级,请使用条件聚合。
SELECT c.Name,
sum(CASE WHEN cb.Priority = 0 THEN 1 else 0 end) as "Unspecified"
sum(case WHEN cb.Priority = 1 THEN 1 else 0 end) as "Low"
sum(case WHEN cb.Priority = 2 THEN 1 else 0 end) as "Medium"
sum(case WHEN cb.Priority = 3 THEN 1 else 0 end) as "High"
FROM TABLE 1 cb
LEFT JOIN Co c ON c.Id = cb.Id
WHERE c.Name LIKE %Name%"
GROUP BY c.name;