SELECT RIGHT(LEFT(a.JobOrders, 16), 3) as OrderSuffix, COUNT(1) as TotalCount
FROM Orders a, Status b
WHERE a.JobOrders = b.JobOrders
AND b.Status = 'Finished'
GROUP BY RIGHT(LEFT(a.JobOrders, 16), 3)
ORDER BY TotalCount Desc
有没有办法在SELECT
个TOP (1)
查询表Date
中的TIME
Status
和RIGHT(LEFT(a.JobOrders, 16), 3) = <3 letter value>
个字段中包含OrderSuffix
?< / p>
我目前正在做的是先得到不同的值RIGHT(LEFT(a.JobOrders, 16), 3) = <3 letter value>
。把它放在数据表上。对于每一行,我发送一个SQL TOP (1)
来获取Date
Time
和{{1}}。
答案 0 :(得分:1)
有关如何执行top-n-per-group
查询的两种常用方法的详细信息,请参阅Get top 1 row of each group问题。
以下查询使用ROW_NUMBER
方法。
WITH
CTE
AS
(
SELECT
RIGHT(LEFT(a.JobOrders, 16), 3) as OrderSuffix
,COUNT(1) OVER (PARTITION BY RIGHT(LEFT(a.JobOrders, 16), 3)) as TotalCount
,b.Date
,b.Time
,ROW_NUMBER() OVER
(PARTITION BY RIGHT(LEFT(a.JobOrders, 16), 3)
ORDER BY b.Date DESC, b.Time DESC) as rn
FROM
Orders a
INNER JOIN Status b ON a.JobOrders = b.JobOrders
WHERE
b.Status = 'Finished'
)
SELECT
OrderSuffix
,TotalCount
,Date
,Time
FROM CTE
WHERE rn = 1
ORDER BY TotalCount Desc;