Select records based on column priority

前端 未结 4 1150
Happy的楠姐
Happy的楠姐 2021-01-23 06:37

First of all, the title of this question is horrible, but I didn\'t find a better way to describe my issue.

There\'s probably a very easy way to do this, but I couldn\'t

相关标签:
4条回答
  • 2021-01-23 07:11

    You can have it like this

    WITH PriorityTable
    AS
    (
        SELECT T.*,
            ROW_NUMBER() OVER (PARTITION BY T.ID
                                ORDER BY PT.ColorPriority )  PriorityColumn
        FROM XX AS T
        INNER JOIN (
            SELECT 'RED' AS f_COLOUR , 1 AS ColorPriority
            UNION
            SELECT 'GREEN' AS f_COLOUR , 2 AS ColorPriority
        ) AS PT
            ON T.f_COLOUR  = PT.f_COLOUR 
    )
    
    SELECT * FROM PriorityTable
    WHERE PriorityColumn = 1
    
    0 讨论(0)
  • 2021-01-23 07:20

    Your query is nearly correct. Just use PRODUCTID and not ID.

    SELECT * 
    FROM xx
    WHERE f_COLOUR = "GREEN"
    UNION
    SELECT * 
    FROM xx 
    WHERE PRODUCTID not in 
                    (SELECT PRODUCTID
                     FROM xx 
                     WHERE f_COLOUR = "GREEN");
    

    SQLFiddle Demo

    0 讨论(0)
  • 2021-01-23 07:29

    I just want to offer that you can do this with a group by:

    select (case when sum(case when colour = 'Green' then 1 else 0 end) > 0
                 then max(case when colour = 'Green' then id end)
                 else max(case when colour = 'Red' then id end)
            end) as id,
           product_id
           (case when sum(case when colour = 'Green' then 1 else 0 end) > 0 then 'Green'
                 else 'Red'
            end) as colour
    from t
    group by product_id
    
    0 讨论(0)
  • 2021-01-23 07:30

    Try this

    SELECT * 
    FROM xx
    WHERE COLOUR = 'GREEN'
    UNION
    SELECT * 
    FROM xx WHERE P_Id not in 
                    (SELECT P_Id
                     FROM Persons 
                     WHERE COLOUR = 'GREEN');
    

    See ALSO SQL FIDDLE DEMO

    0 讨论(0)
提交回复
热议问题