【问题标题】:Write MySQL query with out rollup编写没有汇总的 MySQL 查询
【发布时间】:2022-01-10 11:04:14
【问题描述】:

我有问题。如果没有roll up,我如何编写这个sql 语句? 我想得到相同的结果,但没有汇总。结果应如下图所示。

我的查询

select state, city, sum((sales.retail_price - products.wholesale_price) * 
sales.quantity) as profit 
from products, sales
where sales.product_id = products.product_id
group by state, city WITH ROLLUP
order by state is null, city is null, state, city ;

我的架构

-- Create some tables and insert some rows.
create table products (product_id integer, wholesale_price real);
insert into products (product_id, wholesale_price) values 
    (1, 1.00),
    (2, 2.00);

create table sales (product_id integer, retail_price real, 
    quantity integer, city varchar, state varchar);
insert into sales (product_id, retail_price, quantity, city, state) values 
    (1, 2.00,  1, 'SF', 'CA'),
    (1, 2.00,  2, 'SJ', 'CA'),
    (2, 5.00,  4, 'SF', 'CA'),
    (2, 5.00,  8, 'SJ', 'CA'),
    (2, 5.00, 16, 'Miami', 'FL'),
    (2, 5.00, 32, 'Orlando', 'FL'),
    (2, 5.00, 64, 'SJ', 'PR');

【问题讨论】:

  • 我想得到相同的结果,但没有汇总。是什么原因? PS。创建 3 个单独的查询,每个查询都有自己的分组,然后是 UNION ALL。

标签: mysql sql group-by union union-all


【解决方案1】:

您必须使用 UNION 操作,如下所示: 第一个查询返回按州和城市分组的 SUM,第二个查询仅返回州,第三个查询(没有分组依据)返回所有行

select state, city, sum((sales.retail_price - products.wholesale_price) * 
sales.quantity) as profit 
from products, sales
where sales.product_id = products.product_id
group by state, city
UNION ALL 
select state, NULL, sum((sales.retail_price - products.wholesale_price) * 
sales.quantity) as profit 
from products, sales
where sales.product_id = products.product_id
group by state
UNION ALL
select NULL, NULL, sum((sales.retail_price - products.wholesale_price) * 
sales.quantity) as profit 
from products, sales
where sales.product_id = products.product_id;

【讨论】:

  • 谢谢,但ÙNION ALL 有语法错误Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION ALL select state, NULL, sum((sales.retail_price - products.wholesale_pric' at line 7 0.015 sec
  • @Test:我已经修复了。我删除了 order by 子句。如果你没有,你可以在包装三个查询后在最后添加
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 2014-02-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多