如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中

时间:2011-06-22 12:55:01

标签: tsql

declare  @userid int
set @userid=9846
SELECT TOP 10 
          tagid, 
          [Description]
FROM   tagsuggestion 
WHERE  tagid IN (SELECT **DISTINCT** TOP 10  tagid
             FROM  (SELECT ulpt.tagid, 
                           createddate 
                    FROM   userlocationposttag ulpt 
                            WHERE  ulpt.UserID=@userid                                

                    UNION ALL 
                    SELECT ult.tagid, 
                           createddate 
                    FROM   userlocationtag ult 
                             WHERE  ult.UserID=@userid
                    UNION ALL 
                    SELECT upt.tagid, 
                           createddate 
                    FROM   userprofiletag upt 
                             WHERE  upt.UserID=@userid
) T

             ORDER  BY createddate DESC)  

上述查询是错误如果指定了SELECT DISTINCT,ORDER BY项必须出现在选择列表中。

。但如果我删除 DISTINCT ,则此查询会运行

我想确保清晰度,我还希望通过createddate DESC

保持排序顺序

我的一篇相关帖子是

Last created 10 records from all of the 3 tables

2 个答案:

答案 0 :(得分:2)

您基本上是在告诉查询按不存在的字段对输出进行排序。

您必须将createddate放在select语句中,或者您可以按tagid,[Description]和createddate进行分组,并按createddate排序。

现在,如果您认为在包含不同的createddate时可能会获得重复的tagids和描述,那么请围绕该问题包装另一个查询,并在这两个字段上进行前10个不同。

答案 1 :(得分:1)

好的,所以我们只根据它最近创建的日期关注每个标记,因此我们可以将内部查询构造为:

SELECT tagid,MAX(createddate) as createddate FROM (
SELECT ulpt.tagid, 
       createddate 
FROM   userlocationposttag ulpt 
WHERE  ulpt.UserID=@userid                                
UNION ALL 
SELECT ult.tagid, 
       createddate 
FROM   userlocationtag ult 
WHERE  ult.UserID=@userid
UNION ALL 
SELECT upt.tagid, 
       createddate 
FROM   userprofiletag upt 
WHERE  upt.UserID=@userid
) t
GROUP BY tagid

然后我们可以将其包含在另一个子选项中,并应用前十名:

SELECT TOP 10 tagid FROM (
SELECT tagid,MAX(createddate) as createddate FROM (
SELECT ulpt.tagid, 
       createddate 
FROM   userlocationposttag ulpt 
WHERE  ulpt.UserID=@userid                                
UNION ALL 
SELECT ult.tagid, 
       createddate 
FROM   userlocationtag ult 
WHERE  ult.UserID=@userid
UNION ALL 
SELECT upt.tagid, 
       createddate 
FROM   userprofiletag upt 
WHERE  upt.UserID=@userid
) t
GROUP BY tagid
) t ORDER BY createddate desc

我们不再需要明确(因为GROUP BYMAX已经确保每个标记只出现一次)