如何选择列值已更改的行

时间:2017-10-24 10:45:25

标签: sql-server row common-table-expression

我有一张表格,其中我的列数很少,如下所示:

Cusnbr  Name  LoadNumber
 1       Z      10
 1       Z      9
 1       Z      8
 1       C      7
 1       C      6
 1       C      5
 1       B      4
 1       B      3
 1       A      2
 1       A      1

这只是为了一个cusnbr这样有数百万cusnbr ..

我想要输出如下

Cusnbr  Name  LoadNumber
 1       C      7
 1       B      4
 1       A      2

为此我在sql server 2008中写下面的查询:

;With x as
 (
   Select * ,rn=Row_number() over (order by cusnbr,loadnumber) from table
 )
 select x.* from x left outer join x as y  on x.rn=y.rn+1
 and x.name<>y.name  where y.name is not null

但是我没有在上面的代码中获得所需的输出我还得到了最后 Z 我也不想要这个并且我得到的不规则数据不是我想要的正确形式< / p>

任何帮助将不胜感激!!

像这样我想但却无法获得所需的输出

I use this example

2 个答案:

答案 0 :(得分:0)

虽然我不清楚这个问题,但从输出中猜测我已经尝试了密集等级。我猜你想要具有最高LoadNumber的记录具有相同的名称。

 Select * from cteTrial where LoadNumber in (
 Select MAX(x.LoadNumber) as LoadNumber from (
 Select cusnbr , name , LoadNumber , DENSE_RANK() over (order by Name desc ) 
 as Dense from cteTrial) as x group by x.Dense 
 ) 

如果您可以使用CTE,它将产生更好的性能。

答案 1 :(得分:0)

我按照预期编写了代码

;With cte(Cusnbr , Name , LoadNumber)
AS
(
SELECT 1,'Z', 10 Union all
SELECT 1,'Z', 9  Union all
SELECT 1,'Z', 8  Union all
SELECT 1,'C', 7  Union all
SELECT 1,'C', 6  Union all
SELECT 1,'C', 5  Union all
SELECT 1,'B', 4  Union all
SELECT 1,'B', 3  Union all
SELECT 1,'A', 2  Union all  
SELECT 1,'A', 1
)
SELECT cusnbr, 
       NAME, 
       loadnumber 
FROM   (SELECT *, 
               Row_number() 
                 OVER( 
                   partition BY NAME 
                   ORDER BY loadnumber DESC) AS RNk, 
               Row_number() 
                 OVER( 
                   ORDER BY (SELECT 1)) - 1  AS RNO 
        FROM   (SELECT * 
                FROM   cte)dt)DT2 
WHERE  DT2.rnk = 1 
       AND rno > 0 
ORDER  BY NAME DESC 

结果

cusnbr  NAME    loadnumber
-------------------------
1        C          7
1        B          4
1        A          2