SQL Server:具有多个条件的SELECT值

时间:2015-11-20 00:26:04

标签: sql sql-server

寻找以下问题的SQL解决方案

  

返回USERNUMBER组合WHERE PRIORITY = MIN(PRIORITY) [NULL相当于MAX(PRIORITY + 1)] ...如果是PRIORITY中的关系,使用最低LINEITEM

打破

字段:

USER,
LINEITEM,
NUMBER,
PRIORITY

价值观:(' X'表示所需的组合)

USER    LINEITEM    NUMBER  PRIORITY    
-------------------------------------
1       1           12345   NULL    
1       2           23456   2   
1       3           34567   1           X
2       1           9876    3   
2       2           98765   1           X
2       3           12345   2   
2       4           23456   1   
3       1           23456   NULL        X
3       2           12345   NULL    
4       1           34567   NULL    
4       2           45678   NULL    
4       3           12345   1           X
4       4           12345   2   
4       5           23456   1   

提前致谢。

回应PM 77-1,

我目前的方法:

SELECT table1.user,table1.number
FROM table1
JOIN (
  SELECT user,
  CAST(MIN((COALESCE(priority,999) * 
  (10 ^ (5 - LEN(COALESCE(CAST(priority AS VARCHAR),'999'))))) + 
  lineitem) AS VARCHAR) AS selector 
  FROM table1 GROUP BY user 
  ) AS table2 
  ON table1.user = table2.user 
  AND table1.lineitem = CAST(RIGHT(table2.selector, 1) AS int)
  ORDER BY table1.user;

1 个答案:

答案 0 :(得分:1)

使用ROW_NUMBER

SQL Fiddle

;WITH Cte AS(
    SELECT *,
        ROW_NUMBER() OVER(
            PARTITION BY [User]
            ORDER BY
                CASE WHEN Priority IS NULL THEN 1 ELSE 0 END,
                Priority,
                LineItem
        ) AS rn
    FROM tbl
)
SELECT 
    [User], LineItem, Number, Priority
FROM Cte
WHERE rn = 1