2015-06-16 37 views
0

我如何获得一排与GROUP BY,并形成所有行的总和,而无需使用WITH ROLLUP如何使用SUM和GROUP BY来SUM行和所有?

的错误我得到的是在“字段列表”

未知列“X”
SELECT SUM(orderValue) as x GROUP BY day; 

但是,这只会让我每天的orderValue,但我想总结所有的订单,就好像我没有使用GROUP BY。我知道我可以使用ROLLUP,但我需要它在SELECT中。

〔实施例:

SELECT SUM(orderValue) as x, SUM(x) as total GROUP BY day; 

ID orderValue day 
-- ---------- --- 
1 400   2015-01-01 
2 800   2015-01-01 
3 300   2015-01-01 
4 400   2015-01-01 
5 600   2015-01-01 
6 500   2015-01-01 
7 400   2015-01-02 
8 800   2015-01-02 
9 300   2015-01-02 
10 400   2015-01-02 
11 600   2015-01-02 
12 500   2015-01-02 

x  total 
3000 6000 
3000 6000 
+2

请张贴一些示例数据和预期的O/P –

+0

这些仅仅是数据/ SQL的例子。除此之外,我最终想要做的是计算每个月的平均值。有几件事我做GROUP BY。例如,如果订单是在移动设备上进行的。那么我每天总结移动/桌面和两者的总和。 –

+0

所以,如果这段代码是可行的,将解决我有这个SQL查询的所有问题:D SELECT SUM(orderValue)as x,SUM(x)作为总GROUP BY日; –

回答

1

您可以通过使用交与子查询一起这样做,从同一个表中获取总和

SELECT SUM(orderValue) as x, 
t.total 
FROM table 
CROSS JOIN (SELECT SUM(orderValue) total FROM table) t 
GROUP BY day; 

DEMO

+0

我知道metod,但我不想使用它。我现在的SQL就像20行代码,所以为每个东西总共添加60多行似乎相当可怕...:/ –

1

使用子查询

SELECT SUM(orderValue) as x, (SELECT SUM(orderValue) FROM table) as y from table GROUP BY day; 
0

可以在SELECT语句中使用ROLLUP

SELECT day, SUM(orderValue) as x 
FROM my_table 
GROUP BY day 
WITH ROLLUP; 

这将返回类似

day, x 
-------- 
day1,30 
day2,50 
null,80 
+0

OP没有使用ROLLUP指定,虽然 – PaulF

+0

啊..好吧:)我没有'不知道从你的问题.. –

+0

那么,如果你可以在像sum(WITH ROLLUP/orderValue)的sql中使用它来获得它的值,那么它会很好:D –

0
drop table mySales; 

create table mySales 
(id int not null auto_increment primary key, 
    orderValue int not null, 
    theDate date 
); 

insert mySales (orderValue,theDate) values (100,'2014-01-02'),(600,'2015-01-02'),(9,'2014-07-01'),(1400,'2014-07-02'); 
insert mySales (orderValue,theDate) values (87,'2014-11-02'),(999,'2015-11-30'),(18,'2014-07-01'),(800,'2013-07-02'); 
insert mySales (orderValue,theDate) values (11,'2014-1-20'),(9,'2015-11-04'),(1,'2014-07-08'),(6,'2013-05-02'); 
insert mySales (orderValue,theDate) values (100,'2014-01-02'),(600,'2015-01-02'),(9,'2014-07-01'),(1400,'2014-07-02'); 
insert mySales (orderValue,theDate) values (87,'2014-11-02'),(999,'2015-11-30'),(18,'2014-07-01'),(800,'2013-07-02'); 
insert mySales (orderValue,theDate) values (11,'2014-1-20'),(9,'2015-11-04'),(1,'2014-07-08'),(6,'2013-05-02'); 

select theDate, 
sum(orderValue) as dateTotal, 
(select sum(orderValue) from mySales 
) as grandTotal 
from mySales 
group by theDate 
order by theDate; 

theDate, dateTotal, grandTotal 
2013-05-02, 12, 8080 
2013-07-02, 1600, 8080 
2014-01-02, 200, 8080 
2014-01-20, 22, 8080 
2014-07-01, 54, 8080 
2014-07-02, 2800, 8080 
2014-07-08, 2, 8080 
2014-11-02, 174, 8080 
2015-01-02, 1200, 8080 
2015-11-04, 18, 8080 
2015-11-30, 1998, 8080 


select sum(orderValue) from mySales; 
8080