2009-11-12 53 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.