从表中逐列选择所有列

时间:2012-06-07 15:19:07

标签: sql sql-server

'test_table'包含一个名为vendor的列,char值从1到9,1是最高优先级。 'test_table'还有另一个名为match的列,char值为'I'或'H','I'接收更高的优先级。我想返回ID中唯一值的所有行,按匹配优先级排序,然后是供应商。

TEST_TABLE

ID  Vendor  Match  
 1    3      I  
 1    2      I  
 1    4      H  
 2    1      H  
 2    1      I  
 3    1      H  
 3    2      I  

所需结果

ID  Vendor  Match   
1     2   I  
2     1   I   
3     2   I  


SELECT *
FROM 
    (SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS RowNo, * 
     FROM test_table) x
WHERE RowNo = 1 
ORDER BY ID

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

您需要为匹配列创建一个order by子句(基于ascii值进行字符比较),并在vendor列上创建另一个。您甚至可以删除ascii keyowrd(为了清楚起见,我已经写过),只需按顺序使用列名

试试这个:

 ;With cte as 
  ( 
  Select ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ascii(match) desc ,vendor )
   AS RowNo,  Id,Vendor ,Match 
  FROM test_table
  )
  Select Id,Vendor,Match from cte
  WHERE RowNo = 1 

答案 1 :(得分:1)

SELECT Id,Vendor,Match
FROM 
    (SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID,Match Desc,Vendor Asc) AS RowNo, * 
     FROM test_table ) x
WHERE RowNo = 1 
ORDER BY ID