在SQL GROUP BY中的从属表中搜索

时间:2009-11-12 01:12:41

标签: asp.net sql

几个星期前,我问了一个关于消除SQL INNER JOIN中重复记录的question。我最终使用的代码类似于以下答案:

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 = '...'

有什么方法可以实现这个目标吗?感谢。

1 个答案:

答案 0 :(得分: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.