我试图在使用MS-SQL 2012查询结果的末尾有一个总行,需要一些帮助继承我的查询
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
我在这里做了一些非常错误的事情。
结果应该像
Answer rCount
-------------
One 10
Two 25
Total 35
感谢。
答案 0 :(得分:7)
您无法在联盟的其他部分使用别名。
请尝试以下代码:
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
答案 1 :(得分:3)
由于您使用的是SQL Server,因此可以使用CTE执行此操作。
;WITH Temp AS
(
SELECT PropertyValue As Answer, Count(*) As rCount
FROM QuestionerDetail
WHERE QuestionId = 42 and FormId = 1
GROUP BY PropertyValue
)
SELECT Answer, rCount
FROM Temp
UNION ALL
SELECT 'Total' as Answer, SUM(rCount) as rCount
FROM Temp
答案 2 :(得分:3)
您可以使用以下语法:
WITH Temp AS(
SELECT
PropertyValue As Answer
,Count(*) As rCount
FROM QuestionerDetail AS Temp
where QuestionId = 42 and FormId = 1
GROUP BY PropertyValue
)
SELECT Answer, rCount FROM Temp
UNION ALL
SELECT 'Total', SUM(rCount) FROM Temp
我希望它会对你有所帮助!! 祝你好运:)
答案 3 :(得分:3)
只需添加WITH ROLLUP:
SELECT
PropertyValue As Answer, Count(*) As rCount
FROM
QuestionerDetail AS Temp
GROUP BY PropertyValue WITH ROLLUP
答案 4 :(得分:-1)
我已经在RAILS中创建了这个连接表,所以我希望在底线总共得到price_value。
+----+----------------------------+---------+-------------+
| id | name | item_id | price_value |
+----+----------------------------+---------+-------------+
| | 20 packs | 281 | 500.0 |
| | kingfisher-3l | 145 | 899.0 |
| | triple sec | 185 | 299.0 |
| | jagermeister | 179 | 599.0 |
| | campari | 181 | 389.0 |
| | craganmore 12 yrs | 207 | 998.0 |
| | Tandoori Jhinga | 45 | 450.0 |
| | Chicken Makhmali Kebab | 43 | 320.0 |
| | Irani Fish Tikka | 41 | 400.0 |
| | Indonesian Udag Sambal | 93 | 1500.0 |
| | Tom Yum with veg | 3 | 160.0 |
| | Hot & Sour with veg | 6 | 160.0 |
| | Salad Nicoise | 15 | 255.0 |
| | Lamb Gilafi Seekh | 44 | 400.0 |
| | Spicy wild Prwan Curry | 108 | 500.0 |
| | Wild Mushroom | 2 | 160.0 |
| | Minestrone Alla | 1 | 320.0 |
| | Tom Yum with Chicken | 4 | 360.0 |
| | Wild Mushroom | 2 | 320.0 |
| | Prawn Dim Sum | 18 | 280.0 |
| | Seafood Biryani | 61 | 400.0 |
| | Coconut Panacotta | 130 | 250.0 |
| | singleton 12 yrs | 269 | 11030.0 |
| | don angel silver | 266 | 6354.0 |
| | johnnie walker -gold label | 272 | 13792.0 |
+----+----------------------------+---------+-------------+
这是控制器操作视图代码
def daily_wise_report
@result = Item.select(:name, :price_value, :item_id). joins(:order_items)
respond_to do |format|
format.html
format.csv { send_data @result.to_csv }
format.xls
end