2012-09-13 28 views
1

我一直在嘗試使用MS Query中的手動SQL語句窗口將數據從ODBC連接的數據庫中提取數據(grrr)。我可以看到我想要做什麼,但是我已經掛上了語法(我很確定它是特定於MS Query的)。FROM子句中使用MS中的多個INNER JOIN進行子查詢的語法

問題是這樣的:

我有四個表:waybill, waybill_item, rail_bl,和rail_bl_item,在它們之間包含通過一個運送設施處理的權重信息,與貨物或者被路由到卡車上(運),或軌道(軌)。 waybillrail_bl表分別包含卡車和鐵路貨物的日期數據;而waybill_itemrail_bl_item包含這些項目的權重數據。

我想要一張表格,它將返回每天處理的總重量(包括鐵路和卡車)。 I.E.

DATE | WEIGHT 
date1, (truck_weight_for_date1+rail_weight_for_date1) 
date2, (truck_weight_for_date2+rail_weight_for_date2) 
date3, (truck_weight_for_date3+rail_weight_for_date3) 
etc 

通過執行查詢,

SELECT waybill.creation_date, sum(waybill_item.weight) 
FROM waybill 
INNER JOIN waybill_item 
ON waybill.id = waybill_item.waybill_id 
WHERE waybill.creation_date > '01/01/2012' 
GROUP BY waybill.creation_date 
UNION 
SELECT rail_bl.creation_date, sum(rail_bl_item.total_weight) 
FROM rail_bl 
INNER JOIN rail_bl_item 
ON rail_bl.id = rail_bl_item.rail_bl_id 
WHERE rail_bl.creation_date > '01/01/2012' 
GROUP BY rail_bl.creation_date 
ORDER BY waybill.creation_date DESC 

我能得到一個兩列結果在某一天包含卡車的總權在某一天 和鐵路的總權重在單獨的記錄,所以我的結果是這樣的:

DATE | WEIGHT 
date1, truck_weight_for_date1 
date1, rail_weight_for_date1 
date2, truck_weight_for_date2 
date2, rail_weight_for_date2 
date3, truck_weight_for_date3 
date3, rail_weight_for_date3 
etc 

我打的障礙是,我不能讓MS闕ry接受使用我的上述查詢作爲 子查詢,然後彙總每個日期的記錄。即使試圖用我的查詢作爲子查詢進行測試也不行。

例如,試圖

SELECT * FROM 
(
SELECT waybill.creation_date, sum(waybill_item.weight) 
FROM waybill 
INNER JOIN waybill_item 
ON waybill.id = waybill_item.waybill_id 
WHERE waybill.creation_date > '01/01/2012' 
GROUP BY waybill.creation_date 
UNION 
SELECT rail_bl.creation_date, sum(rail_bl_item.total_weight) 
FROM rail_bl 
INNER JOIN rail_bl_item 
ON rail_bl.id = rail_bl_item.rail_bl_id 
WHERE rail_bl.creation_date > '01/01/2012' 
GROUP BY rail_bl.creation_date 
) 
ORDER BY waybill.creation_date DESC 

返回「無法添加表‘(’」錯誤語法的其他變種返回類似的錯誤

有誰知道 - 。或者即使 - - MS Query能夠像這樣執行子查詢嗎?提前感謝您的幫助

回答

0

爲了使用它作爲子查詢,需要在兩個地方使用別名:首先,列需要一個名稱;其次,派生類表需要一個名字:

select * 
from (SELECT waybill.Creation_date, sum(waybil_item.weight) as Weight 
     . . . 
     union all 
     . . . 
    ) t 
order by 1 desc 

順便說一句,你想要UNION ALL而不是UNION。如果你碰巧在給定的日期有相同的值,UNION會消除它們。

+0

感謝您的反饋,戈登。我現在遇到的問題是簡單地嘗試分配一個別名,即使只有一個INNER JOIN選擇。如果我嘗試'SELECT waybill.creation_date,總和(waybill_item.weight)AS Total_Weight FROM運貨單 INNER JOIN waybill_item ON waybill.id = waybill_item.waybill_id WHERE waybill.creation_date> '01/01/2012' GROUP BY運單.creation_date'權重字段的標題保持空白,並返回到SQL窗口顯示「AS Total_Weight」已消失。有什麼建議麼?我很新。 – PriceHardman

相關問題