需要帮助才能使用Row_Number找到中间行

时间:2015-11-24 16:58:20

标签: sql sql-server

SELECT median.spaid
    ,median.total
    ,ROW_NUMBER() OVER (
        ORDER BY median.total
        ) AS row
FROM (
    SELECT SpaID
        ,COUNT(1) AS Total
    FROM dbo.[Order](NOLOCK)
    WHERE DateCreated BETWEEN '04-01-2014'
            AND '04-30-2014'
    GROUP BY SpaID
    ) AS median
ORDER BY median.total

我的问题是我需要找到列的中间行" Total"使用Row_number。我需要找到哪个" SpaID"与" Total"的中间行相关联。列。

3 个答案:

答案 0 :(得分:0)

这是基于非常稀疏的细节在黑暗中拍摄的,但我认为你正在寻找这样的东西。

with numberedResults as
(
    select spaid
        , ROW_NUMBER() over(order by count(*)) as RowNum
    from [order]
    where DateCreated between '20140401' AND '20140630'
    group by SpaID
)
, Medians as
(
    select MAX(RowNum) / 2 as Median
        , MAX(RowNum) as TotalCount
    from numberedResults
)

select *
from numberedResults r
join Medians m on m.Median = r.RowNum

答案 1 :(得分:0)

以下是查找中位数的一种方法:

SELECT o.*
FROM (SELECT SpaID, COUNT(*) AS Total,
             ROW_NUMBER() OVER (ORDER BY COUNT(*)) as seqnum,
             COUNT(*) OVER () as cnt
      FROM dbo.[Order](NOLOCK)
      WHERE DateCreated BETWEEN '2014-04-01' AND '2014-04-30'
      GROUP BY SpaID
     ) o
WHERE 2*o.seqnum IN (cnt - 1, cnt);

当您有偶数行时,这是近似值。您正在寻找确切的行ID,因此您必须选择中位数之前或之后的位数(在两行之间)。

注意:您应该使用ISO标准格式(YYYYMMDD或YYYY-MM-DD)表达日期常量。第一种是SQL Server中最安全的方式(虽然我个人更喜欢连字符以便于阅读)。

答案 2 :(得分:0)

我建议您不要在查询中依赖ROW_NUMBER,因为使用ROW_NUMBER的结果有时可能无法预测。我知道它看起来很笨重 - 挑战是“中位数”是分组行的中间。以下是我认为适合您的查询:

    SELECT SpaID, d FROM
     (SELECT SpaID, 
      DENSE_RANK() OVER (ORDER BY COUNT(1)) AS d
      FROM dbo.[Order] 
      WHERE DateCreated BETWEEN '04-01-2014'
      AND '04-30-2014'
      GROUP BY SpaID)
    WHERE  D=
     (SELECT ROUND(MAX(D)/2,0)
      DENSE_RANK() OVER (ORDER BY COUNT(1)) AS d
      FROM dbo.[Order] 
      WHERE DateCreated BETWEEN '04-01-2014'
      AND '04-30-2014')