1

I have problem in query. I use posgresql. I need to get total row but with condition "group by"

table qwe 
----------------------------
TIPE   | VAL
----------------------------
1      | 2
2      | 3 
2      | 1
2      | 4
3      | 1
3      | 3

the result I need is

-------------------------
TIPE   | VAL | TOTAL TIPE
-------------------------
1      | 2   | 3
2      | 8   | 3
3      | 4   | 3

the query I've tried so far

select tipe, sum(val), count(tipe) "total tipe" 
from qwe group by tipe order by tipe


-------------------------
TIPE   | VAL | TOTAL TIPE
-------------------------
1      | 2   | 1
2      | 8   | 3
3      | 4   | 2
1
  • how can you get the TOTAL TIPE output like that? Oct 8, 2013 at 10:53

4 Answers 4

2

you can try this one:

select
    tipe, sum(val), count(tipe) over() as "total tipe"
from qwe
group by tipe
order by tipe

sql fiddle demo

You see, instead of counting number of not-null tipe records inside each group, you can count number of not null tipe over the whole resultset - that's why you need over() clause. It's called window functions.

2
  • please explain over clause ...thnks Oct 8, 2013 at 11:03
  • yes.. it works! but I still don't get it how to use over(). Thank you so much
    – muhnizar
    Oct 8, 2013 at 11:16
1

That's a strange request, however, I would suggest that you build a view that returns just the count(tipe) of the table and then join that view in? I haven't tested that but I am pretty sure that it would work.

1
select
    tipe, sum(val), max(cnt) "total tipe"
from qwe
join (select count(distinct(tipe)) "cnt" from qwe) v on true
group by tipe
order by tipe

SQL-Fiddle demo

0
0

Your query is giving correct output . For desired output , i don't know why it seems you require TOTAL TIPE value fixed as 3 .

select tipe, sum(val), 3 as "total tipe" 
from qwe group by tipe order by tipe
2
  • its not a fixed value. Its the total of the row
    – muhnizar
    Oct 8, 2013 at 11:11
  • I think you just hard-coded "total tipe" by 3 instead of calculate the row count
    – nametal
    Oct 8, 2013 at 11:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.