如何使用GROUP BY
获取行的总和,并在不使用WITH ROLLUP
的情况下形成所有行
我得到的错误是'字段列表'中的未知列'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
答案 0 :(得分:1)
您可以通过使用带子查询的交叉连接来获取同一个表中的总和
SELECT SUM(orderValue) as x,
t.total
FROM table
CROSS JOIN (SELECT SUM(orderValue) total FROM table ) t
GROUP BY day;
答案 1 :(得分:1)
使用子查询
SELECT SUM(orderValue) as x, (SELECT SUM(orderValue) FROM table) as y from table GROUP BY day;
答案 2 :(得分:0)
您可以在ROLLUP
语句中使用SELECT
:
SELECT day, SUM(orderValue) as x
FROM my_table
GROUP BY day
WITH ROLLUP;
这将返回类似
的内容day, x
--------
day1,30
day2,50
null,80
答案 3 :(得分: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