如何使用其他列选择唯一字符串来计算列中的字符串

时间:2016-10-04 09:10:56

标签: postgresql

试图解决问题找到了,但这不是我需要的......

select distinct column1, count(column2) from table group by column1;


    column1      column2
    aaa          type1
    bbb          type3
    ccc          type1
    aaa          type1
    aaa          type2
    aaa          type1
    ccc          type3
    aaa          type1
    bbb          type3
    aaa          type3
    aaa          type3

预期结果是:

    aaa type1 = 4, type2 = 1, type3 = 2
    bbb type3 = 2
    ccc type1 = 1, type3 = 2

2 个答案:

答案 0 :(得分:2)

select 
    column1, 
    string_agg(format('%s = %s', column2, count), ', ') counts
from (
    select *, count(column2) 
    from test 
    group by 1, 2
    order by 1, 2
    ) s
group by 1
order by 1

 column1 |             counts              
---------+---------------------------------
 aaa     | type1 = 4, type2 = 1, type3 = 2
 bbb     | type3 = 2
 ccc     | type1 = 1, type3 = 1
(3 rows)

答案 1 :(得分:0)

根据您的预期输出,这是我认为您的目标。

使用COUNT函数和嵌套的CASE语句。

SELECT column1, 
COUNT(CASE column2 WHEN 'type1' THEN 1 ELSE NULL END) AS Type1Count,
COUNT(CASE column2 WHEN 'type2' THEN 1 ELSE NULL END) AS Type2Count,
COUNT(CASE column2 WHEN 'type3' THEN 1 ELSE NULL END) AS Type3Count
FROM Yourtable 
GROUP BY column1

输出:

Column1 Type1Count Type2Count Type3Count
aaa     4          1          2
bbb     0          0          2
ccc     1          0          1

或者完全按照您的意愿制作(不推荐):

SELECT column1, 
'type1 = ' || COUNT(CASE column2 WHEN 'type1' THEN 1 ELSE NULL END) AS Type1Count,
'type2 = ' || COUNT(CASE column2 WHEN 'type2' THEN 1 ELSE NULL END) AS Type2Count,
'type3 = ' || COUNT(CASE column2 WHEN 'type3' THEN 1 ELSE NULL END) AS Type3Count
FROM Yourtable 
GROUP BY column1

输出:

Column1 Type1Count  Type2Count  Type3Count
aaa     type1 = 4   type2 = 1   type3 = 2
bbb     type1 = 0   type2 = 0   type3 = 2
ccc     type1 = 1   type2 = 0   type3 = 1