在现有查询中实现“distinct”选择

时间:2009-10-19 18:08:57

标签: sql sql-server tsql

我有一个现有的,相当冗长的SQL查询。我想选择具有明显mt.ID的记录。我尝试在各个地方插入“SELECT DISTINCT”而没有任何成功。谁能告诉我它应该去哪里?非常感谢。

SELECT *
FROM (select ROW_NUMBER() OVER(ORDER BY " + orderField + @") as RowNum,
              mt.ID as mt_ID,
              mt.title as mt_title,
              [...]
              st.title as st_title,
              [...]
    from  mttable as mt 
    inner join sttable as st on mt.ID =st.ID
    where NOT (st.field=0) AND where mt.title = @title" )
as DerivedTableName
WHERE RowNum between ((@pageIndex - 1) * @pageSize + 1) and @pageIndex*@pageSize

2 个答案:

答案 0 :(得分:1)

您需要在所有未分组的列上使用GROUP BY加上聚合:

SELECT *
FROM (select ROW_NUMBER() OVER(ORDER BY " + orderField + @") as RowNum,
              mt.ID as mt_ID,
              max(mt.title) as mt_title,
              [...]
              max(st.title) as st_title,
              [...]
    from  mttable as mt 
    inner join sttable as st on mt.ID =st.ID
    where NOT (st.field=0) AND where mt.title = @title"
    group by mt.ID )
as DerivedTableName
WHERE RowNum between ((@pageIndex - 1) * @pageSize + 1) and @pageIndex*@pageSize

答案 1 :(得分:1)

问题是每条sttable记录可能有多个mttable条记录。因此,您不需要DISTINCT,而是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.