0

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

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
4

2 回答 2

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 演示

于 2012-09-03T15:43:13.007 回答
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
于 2012-09-04T07:51:00.630 回答