2

To make long story short:

I have table like this

nr   sat   col
1    1     dsag
1    2     gds
1    2     gds
2    1     gdsa
2    2     gf
2    3     gdsa

And expect the result like this:

nr  Sat_1   Sat_2   Sat_3
1   1       2       0
2   1       1       1

I want new column for each row from "SELECT DISTINCT sat" and next group by nr

1
  • 1
    "Long story short" - you'll need to use a COUNT(DISTINCT col) with GROUP BY nr, sat to get the numbers, and a PIVOT to get your desired display. To make this short story longer, please show what you've tried already. Commented Mar 3, 2017 at 20:54

2 Answers 2

6

This can be done using conditional aggregation:

select nr, 
       count(*) filter (where sat = 1) as sat_1, 
       count(*) filter (where sat = 2) as sat_2, 
       count(*) filter (where sat = 3) as sat_3
from the_table
group by nr
order by nr;

Online example: http://rextester.com/YVIR75756

Sign up to request clarification or add additional context in comments.

6 Comments

Yes, I know but I don't want to do it manually because there are much more values in sat column than in this example. It would be perfect if it will create "count line" automatically for each distinct value
@dekarz: you should have mentioned that in your question. But in general that's not possible. The number of columns of a query must be known to the database before it is executed.
I see. Thank you anyway, it seems to be the best answer ! :) But I'm disappointed that I can't do it as i imagined.
According to modern sql, filter is part of the optional "Advanced OLAP operations". Does it qualify as standard?
@GordonLinoff HSQLDB also supports the filter clause
|
2

I like a_horse_with_no_name's answer. This is shorter, although it might be slightly slower:

select nr, 
       sum((sat = 1)::int) as sat_1, 
       sum((sat = 2)::int) as sat_2, 
       sum((sat = 3)::int) as sat_3
from the_table
group by nr
order by nr;

The more typical way to write the query is using case:

select nr, 
       sum(case when sat = 1 then 1 else 0 end) as sat_1, 
       . . .

This happens to be standard SQL that will run in many databases.

3 Comments

The filter() clause is standard SQL as well ;)
@a_horse_with_no_name Is there some place with a chart of standard sql features and which rdbms support it? e.g. like you can find for emca5/6 and browsers ? kangax.github.io/compat-table/es6
Not really, I guess because the SQL standard is not available for free. The only remotely similar comparison I know is: sql-workbench.net/dbms_comparison.html but that is far from being complete, nor is it limited to features from the SQL standard.

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.