将带有自定义标签的数据透视表作为行

时间:2019-09-03 17:56:17

标签: sql oracle

我正在尝试为每个聚合列添加标签。 我做了这个SQL,但我认为它可以缩短。

lib

结果:

xterm.js

我还有其他列,但是如果我使用联合,则此查询将非常长。任何想法将不胜感激。

3 个答案:

答案 0 :(得分:2)

重塑此数据的一种方法实际上是作为UNPIVOT的初步方法(以分配所需的LABEL),然后对扩展的数据集执行单个PIVOT

此方法用初始行扩展来换取更简洁的查询-请注意,这里存在成本折衷和性能影响。

以下是您包含的列的示例:

-数据设置示例:

CREATE TABLE PS_TABLE1(UNIT VARCHAR2(32), NUMBER_OF_ORDERS NUMBER, NUMBER_OF_ITEMS NUMBER, TRANSACTION_DATE DATE);

-- Target Data (a couple records to sum for BOS)
INSERT INTO PS_TABLE1 VALUES ('BOS', 25, 55, TRUNC(SYSDATE -1));
INSERT INTO PS_TABLE1 VALUES ('BOS', 10, 15, TRUNC(SYSDATE -1));
INSERT INTO PS_TABLE1 VALUES ('NYC', 250, 550, TRUNC(SYSDATE -1));
-- Other filler data 
INSERT INTO PS_TABLE1 VALUES ('BOS', 253, 785, TRUNC(SYSDATE -2));
INSERT INTO PS_TABLE1 VALUES ('NYC', 175, 315, TRUNC(SYSDATE -2));
INSERT INTO PS_TABLE1 VALUES ('DEN', 1000, 2000, TRUNC(SYSDATE -1));

然后查询:

SELECT LABEL, BOS, NYC FROM (
    SELECT UNIT, LABEL, COUNT_IN_CATEGORY
    FROM (
        SELECT UNIT, NUMBER_OF_ITEMS AS ITEMS, NUMBER_OF_ORDERS AS ORDERS
        FROM PS_TABLE1
        WHERE TRANSACTION_DATE = TRUNC(SYSDATE) - 1)
        -- Other columns can be added here
        UNPIVOT (COUNT_IN_CATEGORY FOR LABEL IN (ITEMS, ORDERS))
) PIVOT (SUM (COUNT_IN_CATEGORY) FOR UNIT IN ('BOS' AS BOS, 'NYC' AS NYC))
ORDER BY LABEL ASC;

结果:

    LABEL    BOS    NYC
_________ ______ ______
ITEMS         70    550
ORDERS        35    250

答案 1 :(得分:0)

我想可以使用大小写透视法来缩短此查询-

SELECT 'Items'
      ,SUM(CASE WHEN Unit = 'BOS' THEN NUMBER_OF_ITEMS END)
      ,SUM(CASE WHEN Unit = 'NYC' THEN NUMBER_OF_ITEMS END)
FROM PS_TABLE1
WHERE TRANSACTION_DATE = TRUNC(SYSDATE)-1
UNION ALL
SELECT 'Orders'
      ,SUM(CASE WHEN Unit = 'BOS' THEN NUMBER_OF_ORDERS END)
      ,SUM(CASE WHEN Unit = 'NYC' THEN NUMBER_OF_ORDERS END)
FROM PS_TABLE1
WHERE TRANSACTION_DATE = TRUNC(SYSDATE)-1

答案 2 :(得分:0)

(未经测试)

with t as (
  select *
  from PS_TABLE1
  where 
    TRANSACTION_DATE = trunc(sysdate)-1
    and UNIT in ('NYC','BOS')
)

select * from (
  select 'Orders' as Label, UNIT, NUMBER_OF_ORDERS as n   
  from t
  union all
  select  'Items', UNIT, NUMBER_OF_ITEMS 
  from t
)
pivot (SUM(N) FOR ( UNIT) IN ('BOS','NYC'))