这是在 MS SSMS 2016 中。我有两个表 - SHIPMENT_HEADER 和 SHIPMENT_DETAIL。
SHIPMENT_HEADER
shipment_id | customer |
------------|------------|
SH001 | cust1 |
SH002 | cust2 |
Shipment_detail 有类似的列
SHIPMENT_DETAIL
shipment_id | customer | item | requested_qty|
------------|----------|--------|--------------|
SH001 | cust1 | item1 | 2 |
SH001 | cust1 | item2 | 2 |
SH001 | cust1 | item3 | 1 |
SH002 | cust2 | item1 | 2 |
SH002 | cust2 | item2 | 2 |
我想知道是否有可能写一些东西,以便对于每个 shipping_id,它返回 shipping_header 详细信息,下面列出了 shipping_details,所以:
shipment_id | instruction |customer | item | requested_qty|
------------|--------------|---------|--------|--------------|
SH001 | HEADER | cust1 | NULL | 5 |
SH001 | DETAIL | cust1 | item1 | 2 |
SH001 | DETAIL | cust1 | item2 | 2 |
SH001 | DETAIL | cust1 | item3 | 1 |
SH002 | HEADER | cust2 | NULL | 4 |
SH002 | DETAIL | cust2 | item1 | 2 |
SH002 | DETAIL | cust2 | item2 | 2 |
我想可能是一个 UNION 来选择标题然后是详细信息,但是如果我一次查询多个货件,它会选择所有标题然后是所有详细信息,而不是标题详细信息、标题详细信息。
到目前为止,我基本上只是分别选择每一位。这是在考虑 UNION 的情况下编写的,因此如果使用另一种方法,可能不需要某些 NULL 列
SELECT
SH.SHIPMENT_ID 'SHIPMENT_ID',
'HEADER' AS 'INSTRUCTION_TYPE',
SH.CUSTOMER 'CUSTOMER',
NULL 'ITEM',
B.TOTAL_QTY
FROM SHIPMENT_HEADER SH
INNER JOIN (
SELECT SHIPMENT_ID, SUM(REQUESTED_QTY) 'TOTAL_QTY'
FROM SHIPMENT_DETAIL
GROUP BY SHIPMENT_ID
) AS B
ON SH.SHIPMENT_ID = B.SHIPMENT_ID
WHERE SH.SHIPMENT_ID IN ('SH001','SH002')
UNION
SELECT
SD.SHIPMENT_ID,
'SHIPMENT_DETAIL' AS 'INSTRUCTION_TYPE',
SD.CUSTOMER,
SD.ITEM,
SD.REQUESTED_QTY
FROM SHIPMENT_DETAIL SD
WHERE SD.SHIPMENT_ID IN (
'SH001', 'SH002'
)
ORDER BY 1, 2