2017-05-03 90 views
1

我有一个表,其中包含如下的键列和其他列。基于列值的选择性筛选行SQL

enter image description here

Keycolumn是COL1,COL2,COL3,COL4的组合。 对于给定的键列值,Col5有不同的值。 如果键列值在Col5上有多个值,则考虑除“O”以外的任何人。如果所有的staus都是'O',那么考虑'O'。

在上述情况下,我应该从黄色,绿色,蓝色和橙色

+1

(1)用你正在使用的数据库标记你的问题。 –

回答

1

Gordon的查询有效,但如果可能的话,它不遵循有关选择非'O'行的规则。

WITH 
CTE 
AS 
(
    SELECT 
     KeyColumn 
     ,Col1 
     ,Col2 
     ,Col3 
     ,Col4 
     ,Col5 
     ,Col6 
     ,ROW_NUMBER() OVER (PARTITION BY KeyColumn 
      ORDER BY 
       CASE WHEN Col5 = 'O' THEN 1 ELSE 0 END -- put 'O' last 
       ,Col5) as rn -- pick first non-O row 
          -- you can choose other column(s) instead of Col5 here 
    FROM YourTable 
) 
SELECT 
    KeyColumn 
    ,Col1 
    ,Col2 
    ,Col3 
    ,Col4 
    ,Col5 
    ,Col6 
FROM CTE 
WHERE rn = 1 
; 
1

得到4 rows.Each了大多数的数据库,你可以使用ANSI标准row_number()功能。例如:

select t.* 
from (select t.*, 
      row_number() over (partition by keycolumn order by keycolumn) as seqnum 
     from t 
    ) t 
where seqnum = 1; 
+0

行号是一种排序。但事实并非如此。 –