如何聚合sql(HANA)中不同行的值?

时间:2017-12-22 07:46:09

标签: sql hana hana-sql-script

我有一个像这样定义的货运表(如果相关,表格存储在HANA数据库中):

CREATE COLUMN TABLE SHIPMENTS (
    ShipmentID INT PRIMARY KEY,
    Received INT,
    Facility NVARCHAR(10),
    Item NVARCHAR(20)
);

此处,“已收到”列表示收到每批货物的时间点,设施是收到货件的地方,而物料是货件的内容。

我已经填写了这样的数据:

INSERT INTO SHIPMENTS VALUES (1, 0, 'Factory', 'Production machine');
INSERT INTO SHIPMENTS VALUES (2, 0, 'Office', 'Printer');
INSERT INTO SHIPMENTS VALUES (3, 0, 'Factory', 'Coffee maker');
INSERT INTO SHIPMENTS VALUES (4, 1, 'Office', 'Coffee maker');
INSERT INTO SHIPMENTS VALUES (5, 1, 'Factory', 'Fax Machine');
INSERT INTO SHIPMENTS VALUES (6, 2, 'Office', 'Computers');
INSERT INTO SHIPMENTS VALUES (7, 2, 'Factory', 'Fridge');
INSERT INTO SHIPMENTS VALUES (8, 2, 'Factory', 'Freezer');
INSERT INTO SHIPMENTS VALUES (9, 2, 'Office', 'Fax Machine');

我想查询数据库,以便在每个时间点查找到那时已收到的项目。基于另一个线程的答案,我开始这样做:

SELECT Facility, Received, STRING_AGG (Item, ';') as Items
    FROM (
        SELECT * FROM SHIPMENTS 
        ORDER BY Facility, Received
    )
GROUP BY Facility, Received
ORDER BY Facility, Received;

导致

  | FACILITY | RECEIVED | ITEMS
---------------------------------------------------------
1 | Factory  | 0        | Production Machine;Coffee maker
2 | Factory  | 1        | Fax Machine
3 | Factory  | 2        | Fridge;Freezer
4 | Office   | 0        | Printer
5 | Office   | 1        | Coffee maker
6 | Office   | 2        | Computers;Fax Machine

但是,我想要这个

  | FACILITY | RECEIVED | ITEMS
---------------------------------------------------------
1 | Factory  | 0        | Production Machine;Coffee maker
2 | Factory  | 1        | Production Machine;Coffee maker;Fax Machine
3 | Factory  | 2        | Production Machine;Coffee maker;Fax Machine;Fridge;Freezer
4 | Office   | 0        | Printer
5 | Office   | 1        | Printer;Coffee maker
6 | Office   | 2        | Printer;Coffee maker;Computers;Fax Machine

即,每行显示该点接收的内容以及已收到的所有内容。有没有一种很好的方法在SQL中执行此操作?

2 个答案:

答案 0 :(得分:1)

您可以尝试在select子句中使用相关查询来生成所需的csv数据:

SELECT
    Facility,
    Received,
    (SELECT STRING_AGG (s2.Item, ';') FROM SHIPMENTS s2
     WHERE s2.Facility = s1.Facility AND s2.Received <= s1.Received
     GROUP BY s2.Facility) AS ITEMS
FROM SHIPMENTS s1
GROUP BY
    Facility,
    Received
ORDER BY
    Facility;

答案 1 :(得分:1)

使用带有String_Agg函数的ORDER BY子句可能是个好主意,以确保连接符合所需的顺序

select 
distinct Facility, Received,
(
    select string_agg(s.Item, ';' order by Received, ShipmentID) 
    from Shipments s 
    where 
        s.Facility = t.Facility and
        s.Received <= t.Received
    ) as Items
from Shipments t