ORDER BY和DISTINCT在同一个select语句中

时间:2017-09-20 12:31:12

标签: sql sql-server sql-order-by distinct

我计算了一个每日数字,汇总了每个名字中输入的所有数字,因此每个名称下都有重复的行。我希望结果只显示每个用户一个结果,所以我认为最好使用distinct。但是,我还需要通过降序显示结果。这可以在同一个声明中做到吗?

    SELECT DISTINCT
    D.DATE, 
    COALESCE( M.[Team ADJ],D.[Team ADJ], M.[Name]) AS 'Sales Person',
    COALESCE( D.[Team], M.[Team]) AS 'Sales Team',
    isnull(D.[Daily Figure],0) AS [Daily Figure],

    FROM  
    [Daily] D
    FULL OUTER JOIN
    [Month] M ON D.[Name] = F.[Name]
    ORDER BY [Daily Figure] DESC

当前结果

 Date       Sales Person    Sales Team     Daily Figure    Month 
 2017-09-19     FRED         SAM               20           285
 2017-09-19     FRED         SAM               20           285
 2017-09-19     FRED         SAM               20           285
 2017-09-19     TOM          BEN               140          118
 2017-09-19     TOM          BEN               140          118

错误:如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。即使我已将其包含在选择列表中

3 个答案:

答案 0 :(得分:1)

order by部分,您可以通过别名引用该列,例如:

select distinct 
    [Date]
  , coalesce( M.[Team adj],D.[Team adj], M.[Name]) as [Sales Person]
  , coalesce( D.[Team], M.[Team]) as [Sales Team]
  , isnull(D.[Daily Figure],0) as [Daily Figure]
  , [Month]
from  [Daily] D
  full outer join [Month] M 
    on D.[Name] = F.[Name]
order by [Daily Figure] desc

<小时/> 如果没有源表来构建查询,请使用上面的示例演示:

select distinct
    t.Date, 
    [Sales Person],
    [Sales Team],
    isnull(t.[Daily Figure],0) AS [Daily Figure]
from t
order by [Daily Figure] desc

rextester演示:http://rextester.com/PVPHSR35614

返回:

+------------+--------------+------------+--------------+
|    Date    | Sales Person | Sales Team | Daily Figure |
+------------+--------------+------------+--------------+
| 2017-09-19 | tom          | ben        |          140 |
| 2017-09-19 | fred         | sam        |           20 |
+------------+--------------+------------+--------------+

答案 1 :(得分:0)

解决此问题的最佳方法是按列号位置排序。例如。如果列位于第4个位置,请按4&#39;

排序
SELECT DISTINCT 
COALESCE( M.[Team ADJ],D.[Team ADJ], M.[Name]) AS 'Sales Person',
COALESCE( D.[Team], M.[Team]) AS 'Sales Team',
isnull(D.[Daily Figure],0),

FROM  
[Daily] D
FULL OUTER JOIN
[Month] M ON D.[Name] = F.[Name]
ORDER BY 4 DESC

答案 2 :(得分:0)

示例查询未生成您已发布的当前结果。

在不同的顺序中,订单列必须是结果集的一部分。在示例查询中,没有名为Daily Figure的列。如果在没有表达式的情况下使用Daily Figure,则Order By可以正常工作。但是,一旦将其包装在表达式中,它就不再被命名为Daily Figure。

最简单的解决方法是为列添加别名。

, isnull(D.[Daily Figure],0) as [Daily Figure]

*更新*

以下是您可以在任何SQL Server上运行的代码段,其中显示了不同的订单操作。

SELECT DISTINCT
            t.type_desc,
            CAST(t.create_date AS DATE) AS Created
  FROM      sys.tables AS t
  ORDER BY  Created
;