2009-11-12 18 views
0

幾周前,我問了一個question關於消除SQL INNER JOIN中的重複記錄。我結束了使用的代碼類似於下面的回答:在SQL GROUP BY的子表中搜索

SELECT ROW_NUMBER() OVER(ORDER BY " + orderField + @") AS RowNum, 
     mt.ID AS mt_ID, 
     mt.title AS mt_title, 
     [...] 
     MAX(st.title) AS st_title, 
     -- Other aggregates (MAX, MIN, AVERAGE, ...) for all other columns 
     -- from sttable, whatever is appropriate. 
     [...] 
FROM mttable AS mt 
INNER JOIN sttable AS st on mt.ID =st.ID 
WHERE st.field <> 0 AND mt.title = @title 
GROUP BY mt.ID, 
     mt.title 
     -- Group by everything else from mttable. 

這在消除重複作品不夠好,但我現在的問題是,我想在sttable(未分組表執行查詢),GROUP BY消除了這些數據。例如,我希望能夠運行查詢WHERE st.title = '...'

有沒有什麼辦法可以實現這個目標?謝謝。

回答

0

嘗試使用CTE (common table expression),它將首先定義您想要從sttable表中獲取的數據 - 在CTE,過濾器,連接,組等中,您可以在sttable表中執行任何操作。不知道這是否會專門針對你正在嘗試做的事情,但最有可能的。如果你可以提供一些關於你想要做什麼的附加細節(例如,你想在sttable中專門做什麼,在某些字段上過濾等等)。

會是這個樣子:

with stData as 
(
    select st.ID, st.field 
    from sttable st 
    where st.field <> 0 
    -- Add additional filters here 
    and st.someOtherField = something 
) 
SELECT ROW_NUMBER() OVER(ORDER BY orderField) AS RowNum, 
     mt.ID AS mt_ID, 
     mt.title AS mt_title, 
     MAX(st.title) AS st_title, 
     -- Other aggregates (MAX, MIN, AVERAGE, ...) for all other columns 
     -- from sttable, whatever is appropriate. 
FROM mttable AS mt 
INNER JOIN stData AS st 
on mt.ID =st.ID 
WHERE st.field <> 0 
AND mt.title = @title 
GROUP BY mt.ID, 
     mt.title 
     -- Group by everything else from mttable.