简体   繁体   English

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

[英]How can I query records depending on value existance?

Assume I have a table with the following entries: 假设我有一个包含以下条目的表:

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

How do I write a SQL query so that for each ID if category S exists, it should output that record, but if it doesn't exist then it should output the entry which exists. 我如何编写SQL查询,以便对于每个ID(如果存在类别S ,它应该输出该记录,但是如果不存在,那么它应该输出存在的条目。 So in my example I would like to achieve the following result: 因此,在我的示例中,我希望获得以下结果:

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

try, 尝试,

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

I found a more elegant solution :-) 我找到了一个更优雅的解决方案:-)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM