将函数聚合到Group By查询中的特定值

时间:2014-06-18 11:39:42

标签: sql sqlite group-by

我有这些数据(例如):

 id         col1        col2
--------------------------------
 5614       (null)      Y
 5614       Y           (null)  
 5614       Y           (null)  

我想获得一行,告诉我这些字段是否有值Y

 id         col1        col2
 5614       Y           Y

如果没有值Y,则应为N

我的实际查询是这样做的,但我认为它应该是一个更短的方式:

SELECT op.id, 
CASE WHEN (SUM(CASE WHEN col1 = 'S' THEN 1 ELSE 0 END)) > 0 THEN 'S' ELSE 'N' END AS col1,
CASE WHEN (SUM(CASE WHEN col2 = 'S' THEN 1 ELSE 0 END)) > 0 THEN 'S' ELSE 'N' END AS col2  
FROM OPERATOR op LEFT JOIN TRAM_OP tr ON op.id = tr.id AND tr.id2 = 20
WHERE op.id = 5614 GROUP BY op.id

如您所见,我有两张桌子,我需要加入它们以匹配id2键。

3 个答案:

答案 0 :(得分:1)

如果Y是唯一可能的值,那么使用简单的max,您将获得此值或NULL:

SELECT id, max(col1) AS col1, max(col2) AS col2
FROM ...
WHERE ...
GROUP BY id

您可以使用ifnull function

将NULL更改为'N'
SELECT id,
       ifnull(max(col1), 'N') AS col1,
       ifnull(max(col2), 'N') AS col2
FROM ...
WHERE ...
GROUP BY id

答案 1 :(得分:1)

一种方法是使用速记,无需使用某些case语句:

SELECT op.id, 
       (CASE WHEN SUM(col1 = 'S') > 0 THEN 'S' ELSE 'N' END) AS col1,
       (CASE WHEN SUM(col2 = 'S') > 0 THEN 'S' ELSE 'N' END) AS col2  
FROM OPERATOR op LEFT JOIN
     TRAM_OP tr
     ON op.id = tr.id AND tr.id2 = 20
WHERE op.id = 5614
GROUP BY op.id;

您还可以利用'S'>这一事实。 'N'

SELECT op.id, MAX(col1) AS col1, MAX(col2) AS col2  
FROM OPERATOR op LEFT JOIN
     TRAM_OP tr
     ON op.id = tr.id AND tr.id2 = 20
WHERE op.id = 5614
GROUP BY op.id;

但是,这个版本可能会让读取代码的其他人感到困惑。

答案 2 :(得分:0)

Select ID,
case when Col1 > 0 then 'Y' else 'N' end 'COL1', 
case when Col2 > 0 then 'Y' else 'N' end 'COL2' 
from
(
    Select id,SUM(case when Col1 = 'y' then 1 else 0 end)'COL1', SUM(
        case when Col2 = 'y' then 1 else 0 end
    )'COL2'
    from #temp
    group by id
) t