如何选择按不同字段排序的唯一字段?

时间:2015-04-14 10:57:56

标签: sql sql-server tsql

我有这个SQL

SELECT DISTINCT DiscountID
FROM (
   SELECT DiscountID, DateCreated
   FROM PayServiceOperations
   WHERE PayServiceTypeID = 2  
   ORDER BY DateCreated DESC
) 
 AS Discount

我知道子查询中不允许的顺序。但是我还能做什么其他方式呢?

2 个答案:

答案 0 :(得分:1)

使用GROUP BY

SELECT DiscountID, MAX(DateCreated)
FROM PayServiceOperations
WHERE PayServiceTypeID = 2  
GROUP BY DiscountID;

答案 1 :(得分:0)

只是想知道你为什么要在OrderID上使用DISTINCT时创建日期的订单的子查询。你在找这个吗?我的两分钱!

  SELECT DISTINCT DiscountID
  FROM PayServiceOperations
  WHERE PayServiceTypeID = 2 
  ORDER BY DateCreated DESC