如何根据值存在查询记录?

时间:2012-09-03 15:39:27

标签: sql db2

假设我有一个包含以下条目的表:

ID    VALUE    CATEGORY
-----------------------
 1       10    A
 1       20    S
 2       30    S
 2       10    A
 3       50    A
 4       40    C
 5       60    B

如何编写SQL查询,以便对于每个ID,如果存在类别S,它应该输出该记录,但如果它不存在则应输出存在的条目。 所以在我的例子中,我希望得到以下结果:

ID    VALUE    CATEGORY
-----------------------
 1       20    S
 2       30    S
 3       50    A
 4       40    C
 5       60    B

2 个答案:

答案 0 :(得分:1)

试,

SELECT  ID, VALUE, Category
FROM    tableName
WHERE   Category = 'S'
UNION
SELECT  ID, VALUE, Category
FROM    tableName
WHERE   ID NOT IN
                (
                    SELECT  ID
                    FROM    tableName
                    WHERE   Category = 'S'
                )
ORDER BY ID

SQLFiddle Demo

答案 1 :(得分:0)

我找到了一个更优雅的解决方案: - )

SELECT  ID, VALUE, CATEGORY
  FROM  (
      SELECT ID, VALUE, CATEGORY,
          ROW_NUMBER() OVER (PARTITION BY ID) as SEQ_ID
        FROM MY_TABLE
      ORDER BY ID, CATEGORY DESC
  )
 WHERE SEQ_ID = 1