在两个表之间选择值最高的行,同时选择group by中的其他列

ogsagwnx  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(293)

我一直在想这个问题。
提供数据库包含以下列:customer\u id、date、trigger、priority、priorityoverride。
我有一个在priority和priorityoverride之间选择最大值的查询,但我似乎无法同时选择取值的行。
以下是我目前的疑问:

SELECT
Customer_ID,
CASE WHEN offers.PriorityOverride > 0 THEN offers.PriorityOverride ELSE 
Priority END AS 'Priority'
FROM
(
SELECT
    Customer_ID,
    MAX(Priority) AS Priority,
    MAX(PriorityOverride) AS PriorityOverride
FROM
    offers
GROUP BY
    CUstomer_ID
) AS offers

上面的查询选择priority和priorityoverride的最大值,并选择较大的值。
现在,我在选择优先权的日期和触发列时遇到了麻烦。
编辑:更多信息:priorityoverride可以为null或空,但如果它不为空或null,则其值将取代任何优先级。
edit2:这是我更新的查询:

SELECT Customer_ID, Date, Trigger_1, Priority, PriorityOverride
  FROM Offers
  WHERE (Customer_ID, Priority) in (
    SELECT
        Customer_ID,
        CASE WHEN
            MAX(PriorityOverride) > 0
        THEN
            MAX(PriorityOverride)
        ELSE
            MAX(Priority)
        END AS 'Priority'
    FROM
        Offers
    GROUP BY
        Customer_ID
  ) 
  OR (Customer_ID, PriorityOverride) in (
    SELECT
        Customer_ID,
        CASE WHEN
            MAX(PriorityOverride) > 0
        THEN
            MAX(PriorityOverride)
        ELSE
            MAX(Priority)
        END AS 'Priority'
    FROM
        Offers
    GROUP BY
        Customer_ID
  )

但是,上面的查询给了我一个错误“errors:a expression of non-boolean type specified in a context where a condition is expected,near','”

oaxa6hgo

oaxa6hgo1#

您可以使用magest来获取最大值之间的较大值,并使用filter来匹配customer\u id、priority或customer\u id、priorityoverride上的值

select Customer_ID, Date, Trigger, Priority, PriorityOverRide
  from offers 
  where (Customer_ID, Priority) in (
    SELECT
        Customer_ID,
        max( case when Priority >  PriorityOverride
          THEN Priority
          ELSE  PriorityOverride
        end )
    FROM  offers
    GROUP BY  CUstomer_ID
  ) 
  or  (Customer_ID, PriorityOverride) in (
    SELECT
        Customer_ID,
        max(case when Priority >  PriorityOverride
          THEN Priority
          ELSE  PriorityOverride
        end )
    FROM  offers
    GROUP BY  CUstomer_ID
  )

相关问题