如何根据条件创建sql选择?

时间:2016-03-02 10:29:33

标签: sql postgresql

我有以下数据库,显示属性的特征如下:

attributeId | attributeCode | groupCode
------------+---------------+-----------
1           | 10            | 50
1           | 10            | 50
1           | 12            | 50

我想要的选择结果是:

attributeId | groupcount | code10 | code12
------------+------------+--------+--------
1           | 1          | 2      | 1

这意味着:attributeId = 1只有一个groupCode(50),其中attributeCode=10出现2次,attributeCode=12出现1次。

当然以下内容无效,但您可以了解我想要实现的目标:

select attributeId,
       count(distinct(groupCode)) as groupcount,
       attributeCode = 10 as code10, 
       attributeCode = 12 as code12
from table
group by attributeId;

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT attributeId, COUNT(DISTINCT groupCode) AS groupcount,
       COUNT(CASE WHEN attributeCode = 10 THEN 1 END) AS code10,
       COUNT(CASE WHEN attributeCode = 12 THEN 1 END) AS code12
FROM mytable
GROUP BY attributeId

http://ujyaaloonline.com/audios/programAudios/1a8fdf5d0433ed581bbcee74836b3305.mp3