T-SQL:在子查询中搜索

时间:2015-07-13 08:08:12

标签: sql-server tsql

我的数据库中有以下数据:

    Docnr   Weight1 Weight2  
    F4879   479,43  484,62  
    F6463   505,43  509,62
    F6464   505,43  509,62
    F8461   531,43  535,62
    F9716   532,43  561,62
    F6461   533,43  561,62
    F6137   609,43  613,62
    F9843   609,43  613,62
    F9764   635,43  613,62

现在我想要输出一个额外的列'警告'像这样:

    Docnr   Weight1 Weight2 Warning
    F4879   479,43  484,62  1
    F6463   505,43  509,62  2
    F6464   505,43  509,62  1
    F8461   531,43  535,62  3
    F9716   532,43  561,62  2
    F6461   533,43  561,62  1
    F6137   609,43  613,62  2
    F9843   609,43  613,62  1
    F9764   635,43  613,62  

计算&#39;警告&#39;: Warning = number of rows ahead where value(Weight2) <= value(Weight1)

示例:

   Column 'Warning' in row 1 is 1 because  
   Check 484,62 <= 505,43: Yes -> 1 row ahead    
   Column 'Warning' in row 2 is 2 because   
   Check 509,62 <= 505,43: No  
   Check 509,62 <= 531,43: Yes -> 2 rows ahead  
   Column 'Warning' in row 4 is 3 because   
   Check 535,62 <= 532,43: No  
   Check 535,62 <= 533,43: No  
   Check 535,62 <= 609,43: Yes -> 3 rows ahead  

是否有人知道如何编写我的语句以输出上述结果?

1 个答案:

答案 0 :(得分:0)

子查询应该有效,但需要订单列作为基线

declare @t table (Docnr varchar(10), weight1 float, weight2 float)

insert into @t
values
('F4879', 479.43, 484.62), 
('F6463', 505.43, 509.62), 
('F6464', 505.43, 509.62), 
('F8461', 531.43, 535.62), 
('F9716', 532.43, 561.62), 
('F6461', 533.43, 561.62), 
('F6137', 609.43, 613.62), 
('F9843', 609.43, 613.62), 
('F9764', 635.43, 613.62)


;with r as
(
    select Docnr, weight1, weight2
        , ROW_NUMBER() over(order by weight1) as nbr
    from @t
)

select r0.nbr, min(r.nbr) - r0.nbr
from r as r0 join r on r0.weight2 < r.weight1
group by r0.nbr