如何按列显示结果?

c9x0cxw0  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(274)

我有几个类似的问题。并希望按列获取结果。有可能吗?我该怎么办?“union”的语法正确吗?
例子:

select(
(select total, amount FROM table_1 where sale_type = "type_1" GROUP BY 
total WITH ROLLUP),
(select total, amount FROM table_1 where sale_type = "type_2" GROUP BY 
total WITH ROLLUP),
(select total, amount FROM table_1 where sale_type = "type_3" GROUP BY 
total WITH ROLLUP),
(select total, amount FROM table_1 where sale_type = 
"type_4" GROUP BY 
total WITH ROLLUP),ORDER BY total);

谢谢!
结果表:

total    type_1     type_2   type_3   type_4
  ...      ...        ...      ...      ...
eqzww0vc

eqzww0vc1#

这个答案是推测性的,因为您没有向我们显示任何示例数据,但我可能建议您需要基于 sale_type . 如果是这样,那么下面的查询应该是您想要的:

SELECT
    total,
    SUM(CASE WHEN sale_type = 'type_1' THEN amount ELSE 0 END) AS sum_1,
    SUM(CASE WHEN sale_type = 'type_2' THEN amount ELSE 0 END) AS sum_2,
    SUM(CASE WHEN sale_type = 'type_3' THEN amount ELSE 0 END) AS sum_3,
    SUM(CASE WHEN sale_type = 'type_4' THEN amount ELSE 0 END) AS sum_4
FROM table_1
GROUP BY total WITH ROLLUP;

相关问题