0

I have a table t that looks like this (which is itself the result of a long SQL query):

 ID | Name | Active | Sales ---------------------------------------------- 1 Amy t 50 2 Bill f 4 3 Chip t 127 4 Dana t 543 5 Eve f 20 

I'm looking to combine the inactive users ("Active" = f) so that I end up with a resultant table like this:

 ID | Name | Active | Sales ---------------------------------------------- 1 Amy t 50 3 Chip t 127 4 Dana t 543 0 - f 24 

Is there a way to do this without repeating the initial query to get that table?

4 Answers 4

3

Here is a simple way:

select id, name, active, sales from t where active union all select 0, NULL, f, sum(sales) from t where not active; 

If this is the result of a complex view, you might not want to reference it twice. If so, you can use aggregation:

select (case when active then id end) as id, (case when active then name end) as name, active, sum(sales) as sales from t group by (case when active then id end), (case when active then name end) as name, active; 
Sign up to request clarification or add additional context in comments.

3 Comments

you're right, I don't want to reference it twice. I will try out your second code block.
for the second query, the second case when is wrong
"case when active then name" would be good, use the answer from @avb and mix it with this one to get the correct query.
3

used another table with boolean for sampling (used kvazi int, boolean and kvazi text attributes) ((different from above by having not union and just one case))(((used sum as I thought that's what you want - aggregate over a case))):

t=# select case when not rolsuper then '-' else rolname::text end , rolsuper , sum(oid::text::int) from pg_roles group by case when not rolsuper then '-' else rolname::text end,rolsuper; rolname | rolsuper | sum ----------+----------+-------- - | f | 144394 vao | t | 16555 postgres | t | 10 (3 rows) 

so for you should be smth like:

select case when not active then 0 else id end , case when not active then '-' else name end , active , sum(sales) from t group by case when not active then 0 else id end , case when not active then '-' else name end , active; 

Comments

2
SELECT ID ,Name ,Active ,Sales FROM my TABLE WHERE Active = 't' UNION SELECT 0 ,'' ,Active ,COUNT(Sales) FROM my TABLE WHERE Active = 'f' GROUP BY Active 

Comments

0

and here's without unions:

select IIF(Active = 'f', 0, ID) ID, IIF(Active = 'f', '-', Name) Name, Active, SUM(Sales) Sales from t group by IIF(Active = 'f', 0, ID), IIF(Active = 'f', '-', Name), Active 

1 Comment

Good query but IIF is for access not postgresql

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.