[英]How do I combine multiple tables? (First has data from this month, second has all other previous data)
我希望創建一個查詢,顯示運輸編號、集裝箱 ID、跟蹤號、上次移動到的位置、移動的時間以及移動的人。
這就是問題所在。 我們最近將超過 30 天的任何內容備份或交易歷史記錄到另一個表中。
所以我有表 transaction_history,它提供了從今天到 30 天前的所有內容,我有表 AR_transaction_history,它提供了其他所有內容(從 31 天前開始。)
我需要能夠為用戶創建輸入容器 ID、跟蹤號或運輸 ID 的提示。
我需要幫助加入這兩個表來創建一個包含所有記錄的表。 我嘗試了 union all,但它不適用於我的提示。 我嘗試了一個 isnull 語句,但也沒有用。 這是代碼。
select
th.reference_id,
th.container_id 'Container ID',
sc.tracking_number 'Tracking Number',
max(th.DATE_TIME_STAMP) 'Time of Last Touch',
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name
END AS 'User Name',
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.location
END AS 'Location'
from TRANSACTION_HISTORY th
inner join TRANSACTION_HISTORY th1 on th1.CONTAINER_ID = th.CONTAINER_ID
inner join SHIPPING_CONTAINER sc on sc.CONTAINER_ID = th.CONTAINER_ID
group by th.container_id, sc.tracking_number, th1.DATE_TIME_STAMP, th1.USER_NAME, th1.LOCATION, th.REFERENCE_ID
Having
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name
END is not null
UNION ALL
select
th.reference_id,
th.container_id 'Container ID',
sc.tracking_number 'Tracking Number',
max(th.DATE_TIME_STAMP) 'Time of Last Touch',
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name
END AS 'User Name',
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.location
END AS 'Location'
from AR_TRANSACTION_HISTORY th
inner join AR_TRANSACTION_HISTORY th1 on th1.CONTAINER_ID = th.CONTAINER_ID
inner join AR_SHIPPING_CONTAINER sc on sc.CONTAINER_ID = th.CONTAINER_ID
group by th.container_id, sc.tracking_number, th1.DATE_TIME_STAMP, th1.USER_NAME, th1.LOCATION, th.REFERENCE_ID
Having
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name
END is not null
在子查詢中執行UNION ALL
,並保持原始查詢的 rest 不變。 這是最簡單的方法,無需查看(聚合)查詢的整個邏輯。
SELECT
....
FROM
(
SELECT * FROM TRANSACTION_HISTORY
UNION ALL SELECT * FROM AR_TRANSACTION_HISTORY
) as th
INNER JOIN SHIPPING_CONTAINER sc on sc.CONTAINER_ID = th.CONTAINER_ID
GROUP BY ...
注意:一般情況下, SELECT *
和UNION ALL
相處得不好。 此答案假定表TRANSACTION_HISTORY
和AR_TRANSACTION_HISTORY
具有完全相同的結構(列和數據類型)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.