我有两种不同的观点:
查看#1:Get_MTD_Booking
SELECT
CAST(tbm.booking_datetime AS DATE) AS [Date],
COUNT(tbm.booking_id) AS [TotalShipments],
SUM(tbd.qty) AS [TotalPcs],
SUM(tbd.weight) AS [TotalWeight],
SUM(tbm.amount_wr) AS [Amount],
'Booking' AS [Status],
tbm.source_terminal_id, tbm.source_ccp_id
FROM
tbl_booking_master tbm
INNER JOIN
tbl_booking_detail tbd ON tbm.booking_id = tbd.booking_id
GROUP BY
CAST(tbm.booking_datetime AS DATE),
tbm.source_terminal_id, tbm.source_ccp_id
查看#2:Get_MTD_Delivery
:
SELECT
CAST(tdm.delivery_datetime AS DATE) AS [Date],
COUNT(tdd.BarCode) AS [TotalShipments],
SUM(tbd.qty) AS [TotalPcs],
SUM(tbd.weight) AS [TotalWeight],
0 AS [Amount],
'Delivery' AS [Mode],
tbm.destination_terminal_id,
tbm.destination_ccp_id
FROM
tbl_delivery_master tdm
INNER JOIN
tbl_delivery_detail tdd ON tdm.delivery_id = tdd.delivery_id
AND tdm.booking_id = tdd.booking_id
INNER JOIN
tbl_booking_master tbm ON tdm.booking_id = tbm.booking_id
INNER JOIN
tbl_booking_detail tbd ON tbm.booking_id = tbd.booking_id
GROUP BY
CAST(tdm.delivery_datetime AS DATE),
tbm.destination_terminal_id, tbm.destination_ccp_id
每个视图返回相同数量的列:
1:日期
2:TotalShipments
3:TotalPcs
4:TotalWeight
5:金额
6:模式
7:DestinationTerminalId
8:DestinationCCPID
我真正想要的是以这种格式显示所有这些结果:
|Date | DestinationId | DestinationCCP | TotalShipments_Booked | TotalPcs_Booked | TotalWeight_Booked |TotalShipments_Delivered | TotalPcs_Delivered | TotalWeight_Delivered |
我希望结果按日期和目标ID分组。
我曾尝试为此编写子查询,但它没有帮助。任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
您可以尝试加入两个观点。当然存在给定货物与任何实际交付不匹配的风险,在这种情况下,对于这样的记录将存在少量NULL
字段。但是,假设每次交货都是在实际发货的某个时刻发生的,那么这应该合理地运作。
SELECT
t1.[DATE],
t1.[TotalShipments] AS TotalShipmentsBooked,
t2.[TotalShipments] AS TotalShipmentsDelivered,
t1.[TotalPcs] AS TotalPcsBooked,
t2.[TotalPcs] AS TotalPcsDelivered,
t1.[TotalWeight] AS TotalWeightBooked,
t2.[TotalWeight] AS TotalWeightDelivered,
t1.[TotalAmount] AS TotalAmountBooked,
t2.[TotalAmount] AS TotalAmountDelivered,
t1.[source_terminal_id] AS TerminalId,
t1.[source_ccp_id] AS CCPID
FROM Get_MTD_Booking t1
LEFT JOIN Get_MTD_Delivery t2
ON t1.[DATE] = t2.[DATE] AND
t1.source_terminal_id = t2.destination_terminal_id AND
t1.source_ccp_id = t2.destination_ccp_id;