我想從特定格式的數據庫檢索數據以掛鉤到儀表板應用程序。我需要一個名爲「導入」的列,其中包含數字,另一列叫做「導出」,其中包含相關計數。我現在有下面的查詢,但它只返回一個導入列,我已驗證有相關數據顯示爲導出。有任何想法嗎?添加我得到的結果截圖...SQL聯合查詢不返回這兩列
SELECT count(*) as "Import", a.ship_id "Ship"
FROM SERVICE_EVENTS a JOIN CONTAINERS b ON a.eq_nbr = b.nbr
WHERE (
(to_char(sysdate, 'HH24') between '07' and '17' and a.performed between trunc(sysdate) + 7/24 and sysdate and category = 'I')
OR
(to_char(sysdate, 'HH24') between '18' and '23' and a.performed between trunc(sysdate) + 18/24 and sysdate and category = 'I')
OR
(to_char(sysdate, 'HH24') between '00' and '06' and a.performed between trunc(sysdate - 1) + 18/24 and sysdate and category = 'I')
)
AND a.TSERV_ID in ('LOAD', 'DISCHARGE') group by a.ship_id
UNION
SELECT count(*) as "Export", a.ship_id "Ship"
FROM SERVICE_EVENTS a JOIN CONTAINERS b ON a.eq_nbr = b.nbr
WHERE (
(to_char(sysdate, 'HH24') between '07' and '17' and a.performed between trunc(sysdate) + 7/24 and sysdate and category = 'E')
OR
(to_char(sysdate, 'HH24') between '18' and '23' and a.performed between trunc(sysdate) + 18/24 and sysdate and category = 'E')
OR
(to_char(sysdate, 'HH24') between '00' and '06' and a.performed between trunc(sysdate - 1) + 18/24 and sysdate and category = 'E')
)
AND a.TSERV_ID in ('LOAD', 'DISCHARGE') group by a.ship_id
;
什麼是您預期的結果? –
UNION不會將額外的數據添加爲列(向右),它會將額外的行添加到結果中(在現有列中)。您可以通過添加另一列「type」來區分這兩個列(否則可能很難區分它們),或者做一些更復雜的事情,比如@vkp在他的回答中做的事情。 – Thilo
@AaronBertrand固定 – runelynx