2011-08-02 64 views
0

我不是SQL大師,無論如何,我很難包裝我的頭如何做一個特定的SQL查詢。需要幫助設計一個SQL語句

我有三個Oracle數據庫表,MBRHISTDETL,LOCINFODETL和METERCHGDETL。從MBRHISTDETL我會得到以下字段:MBRSEP,LOCATION,BILLTYPE,BILLMOYR,KWH。從LOCINFODETL(LOCATION是關鍵)我會得到DIST,CYCLE,ADDR1。從METERCHGDETL(MBRSEP是關鍵)我會得到METER。

到目前爲止,使用我的查詢,我能夠從MBRHISTDETL和LOCINFODETL獲取所需的所有信息。但是,我現在不太清楚如何將下一個表METERCHRDETL添加到查詢語句中。有人可以幫我解決這個問題嗎?

這裏是我的查詢,到目前爲止:

SELECT LOCINFODETL.LOCATION AS L.LOCATION, 
    LOCINFODETL.DIST, LOCINFODETL.CYCLE, 
    LOCINFODETL.ADDR1, MBRHISTDETL.MBRSEP, 
    MBRHISTDETL.LOCATION AS M.LOCATION, 
    MBRHISTDETL.BILLTYPE, MBRHISTDETL.BILLMOYR, 
    MBRHISTDETL.KWH 
FROM MBRHISTDETL 
    INNER JOIN L.LOCINFODETL ON H.MBRHISTDETL.LOCATION = L.LOCATION 
WHERE MBRHISTDETL.BILLTYPE = '09' 
    AND CAV_MBRHISTDETL.BILLMOYR <> '9999' 
    AND SUBSTR(LOCINFODETL.CYCLE,0,2) = '04' 
    AND LOCINFODETL.DIST = '16' 
+1

Oracle有「表」而不是「文件」 – APC

+0

對不起,APC。我是一位老的AS/400程序員,我們總是把數據庫表稱爲「文件」。我不知道爲什麼,因爲「表格」是正確的術語。 – Kevin

回答

3

這應該讓你開始 - 但你需要知道哪個字段鏈接你的M表。

另外 - 只是一個樣式提示 - 如果你第一次嘗試從SQL中理解特別是 - 你將能夠證明你的SQL更容易,如果你格式化一點點vertcially。我的風格可能並不是最好的,但是你可以看看它是否讓事情變得更容易閱讀。

SELECT 
    L.LOCATION AS L_LOCATION, 
    L.DIST, 
    L.CYCLE, 
    L.ADDR1, 
    H.MBRSEP, 
    H.LOCATION AS H_LOCATION, 
    H.BILLTYPE, 
    H.BILLMOYR, 
    H.KWH, 
    M.METER 
FROM 
     MBRHISTDETL H 
    INNER JOIN 
     LOCINFODETL L 
    ON 
     H.LOCATION = L.LOCATION 
    INNER JOIN 
     METERCHRDETL M 
    ON M.___KEY___ = H.___KEY___ -- or perhaps L.___KEY___ 
WHERE 
     H.BILLTYPE = '09' 
    AND H.BILLMOYR <> '9999' 
    AND SUBSTR(L.CYCLE,0,2) = '04' 
    AND L.DIST = '16' 
0

像這樣的事情應該工作,雖然我不是你正在使用的前綴的100%。

SELECT LOCINFODETL.LOCATION AS L.LOCATION, 
    LOCINFODETL.DIST, LOCINFODETL.CYCLE, 
    LOCINFODETL.ADDR1, MBRHISTDETL.MBRSEP, 
    MBRHISTDETL.LOCATION AS M.LOCATION, 
    MBRHISTDETL.BILLTYPE, MBRHISTDETL.BILLMOYR, 
    MBRHISTDETL.KWH, METERCHGDETL.METER 
FROM MBRHISTDETL 
    INNER JOIN L.LOCINFODETL ON H.MBRHISTDETL.LOCATION = L.LOCATION 
    INNER JOIN METERCHGDETL ON H.MBRHISTDETL.MBRSEP = METERCHGDETL.MBRSEP 
WHERE MBRHISTDETL.BILLTYPE = '09' 
    AND CAV_MBRHISTDETL.BILLMOYR <> '9999' 
    AND SUBSTR(LOCINFODETL.CYCLE,0,2) = '04' 
    AND LOCINFODETL.DIST = '16'