如何与列名一起显示多个查询结果?

问题描述

我有四个查询,数据取自同一个表。

select sum(unit_sold) as total_unit_sold 
from tewt 
where order_priority = 'HH'

union all

select avg(unit_sold) as average_unit_sold 
from tewt 
where order_priority = 'H'

union all

select max(unit_sold) as maximum_unit_sold 
from tewt 
where order_priority = 'M'

union all

select min(unit_sold) as minimum_unit_sold 
from tewt 
where order_priority = 'L';

我使用“Union All”来描述没有行和列名称的所有结果。

结果:

total_unit_sold (numeric)
1. 2401
2. 5362.00
3. 7699
4. 6184

但我不知道如何将它们与每个结果的列/行名称一起显示

任何帮助将不胜感激。

谢谢

解决方法

将每个选择作为列表达式而不是UNION ALL将它们放在一起;这允许您为每个子选择分配一个列名。

SELECT
    (select sum(unit_sold) from tewt where order_priority='HH') as total_unit_sold,(select avg(unit_sold) from tewt where order_priority='H') as average_unit_sold,(select max(unit_sold) from tewt where order_priority='M') as maximum_unit_sold,(select min(unit_sold) from tewt where order_priority='L') as minimum_unit_sold;

不清楚“行名称”是什么意思 - 您有 4 个值,所以它要么是 4 行 x 1 列,就像您已有的一样,要么是 1 行 x 4 列,如上所示。如果您想要的是 4x4,行标记为“HH”、“H”、“M”、“L”,列标记为现有查询中的标记,以及新单元格的 NULL,这也是可能的,但涉及更多如果是这样的话,我会让你澄清一下。

,

如果对 4 种情况使用 CASE 表达式,则可以在 1 个查询中完成:

SELECT order_priority,CASE order_priority
         WHEN 'HH' THEN 'total_unit_sold' 
         WHEN 'H' THEN 'average_unit_sold'
         WHEN 'M' THEN 'maximum_unit_sold'
         WHEN 'L' THEN 'minimum_unit_sold'
       END description,CASE order_priority
         WHEN 'HH' THEN SUM(unit_sold) 
         WHEN 'H' THEN AVG(unit_sold) 
         WHEN 'M' THEN MAX(unit_sold) 
         WHEN 'L' THEN MIN(unit_sold) 
       END amount
FROM tewt 
WHERE order_priority IN ('HH','H','M','L')
GROUP BY order_priority 

如果您希望将所有值作为 1 行中的 4 列,您可以使用条件聚合来实现:

SELECT SUM(CASE WHEN order_priority = 'HH' THEN unit_sold END) total_unit_sold,AVG(CASE WHEN order_priority = 'H' THEN unit_sold END) average_unit_sold,MAX(CASE WHEN order_priority = 'M' THEN unit_sold END) maximum_unit_sold,MIN(CASE WHEN order_priority = 'L' THEN unit_sold END) minimum_unit_sold       
FROM tewt 
WHERE order_priority IN ('HH','L');

或者:

SELECT SUM(unit_sold) FILTER (WHERE order_priority = 'HH') total_unit_sold,AVG(unit_sold) FILTER (WHERE order_priority = 'H') average_unit_sold,MAX(unit_sold) FILTER (WHERE order_priority = 'M') maximum_unit_sold,MIN(unit_sold) FILTER (WHERE order_priority = 'L') minimum_unit_sold       
FROM tewt 
WHERE order_priority IN ('HH','L');

如果 'HH''H''M''L'order_priority 的唯一可能值,您可以删除 WHERE 子句。

,

在 Postgres 中,您将使用条件聚合,它使用 filter 子句:

select sum(unit_sold) filter (where order_priority = 'HH') as hh_total_unit_sold,sum(unit_sold) filter (where order_priority = 'H') as h_total_unit_sold,sum(unit_sold) filter (where order_priority = 'M') as m_total_unit_sold,sum(unit_sold) filter (where order_priority = 'L') as l_total_unit_sold       
from tewt ;