1

Trying to solve the problem find that, but it is not what i need...

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

Expected result is:

    aaa type1 = 4, type2 = 1, type3 = 2
    bbb type3 = 2
    ccc type1 = 1, type3 = 2
1
  • then use column_2 for grouping Commented Oct 4, 2016 at 9:14

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

From your expected output this is what I think your are after.

Use a COUNT function with a nested CASE statement.

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

Output:

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

Or to make it exactly as you wanted it (not recommended):

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

Output:

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

6 Comments

thanks a lot, but data in table is dynamic, and what if i don't know values in column2 from the begining? i can't write something like WHEN 'type1'
You could use a SQL Pivot Function more than likely.
@a_horse_with_no_name Duly noted and amended :)
Please, and what about if there is one else column0, how make query show values that corresponding column1?
in previous context query
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.