获取TOP(1)状态表的日期和时间

时间:2018-06-04 04:34:49

标签: sql sql-server

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

有没有办法在SELECTTOP (1)查询表Date中的TIME StatusRIGHT(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}}。

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;