Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a total row to the end of query result

Tags:

sql

sql-server

Im trying to have a Total row at the end of query result im using MS-SQL 2012, need some help heres my query

SELECT
PropertyValue As Answer,Count(*) As rCount 
FROM 
QuestionerDetail AS Temp
where 
QuestionId = 42 and FormId = 1 
GROUP BY PropertyValue
Union All
SELECT 'Total',sum(rCount) 
FROM 
temp

Im doing something really wrong here.

The Result should be like

Answer rCount
-------------
 One     10
 Two     25
 Total   35

Thanks.

like image 888
Mohsin Mushtaq Avatar asked Feb 12 '26 01:02

Mohsin Mushtaq


1 Answers

You can't use the alias in another part of the union.

Try below instead:

SELECT
PropertyValue As Answer, Count(*) As rCount 
FROM 
QuestionerDetail AS Temp
where 
QuestionId = 42 and FormId = 1 
GROUP BY PropertyValue
Union All
SELECT 'Total', COUNT(*) 
FROM 
QuestionerDetail 
where 
QuestionId = 42 and FormId = 1 
like image 188
xdazz Avatar answered Feb 14 '26 14:02

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!