简单 SQL 查询的建议

Suggestion of a simple SQL query

我有以下 table:

state       product_a          product_b          final_score
FL          Apple              Açai Berries       9
FL          Apricot            Banana             15
FL          Avocado            Coconut            5
FL          Bilberry           Apricot            17
FL          Blackcurrant       Apricot            6
FL          Blackcurrant       Boysenberry        12
FL          Blueberry          Avocado            11
FL          Blueberry          Cantaloupe         6
FL          Cantaloupe         Coconut            1
FL          Currant            Blackcurrant       5
FL          Cherry             Currant            10
FL          Cherimoya          Cherry             6
FL          Cherimoya          Date               14
FL          Cloudberry         Blueberry          16
FL          Coconut            Apricot            14
FL          Cranberry          Damson             1
FL          Date               Banana             5
NY          Apricot            Blackcurrant       5
NY          Apricot            Dragonfruit        15
NY          Avocado            Cherimoya          16
NY          Avocado            Coconut            18
NY          Banana             Damson             14
NY          Bilberry           Apricot            16
NY          Bilberry           Avocado            1
NY          Blackberry         Blackcurrant       20
NY          Blackberry         Cherimoya          12
NY          Blackcurrant       Damson             19

基于"state"和"product_A"我需要return"product_B"最高"final_score"。 例如,如果我检查 NY "state"、"product_A" Blackberry,我希望查询 return Blackcurrant。

例如,我使用了以下查询:

select product_b from PRODUCTSUGGESTION a,
       (select max(final_score) maxscore from PRODUCTSUGGESTION
       where product_A like '%Blackcurrant%' and state like 'FL') r                   
where r.maxscore=final_score and product_A like '%Blackcurrant%' and state like 'FL'

输出将是:Boysenberry

我上面提出的查询给了我想要的输出。但是,我知道联接会增加查询的复杂性。谁能建议另一种使用更简单查询的方法?

您需要先计算最高分数。然后连接两个表以获取名称。

SQL Fiddle Demo 这使用 sql server cte,MySql 需要内部 select 代替。

WITH maxScore as (
  SELECT state, product_a, max(final_score) as final_score
  FROM Table1
  GROUP BY state, product_a
)
SELECT t.*, m.final_score
FROM Table1 t
inner join maxScore m
   on t.state = m.state
   and t.product_a = m.product_a
   and t.final_score = m.final_score

这对我来说似乎太简单了,但是你开始吧:

SELECT product_b FROM PRODUCTSUGGESTION
WHERE state = 'FL' AND product_a = 'Blackcurrant'
ORDER by final_score DESC FETCH FIRST 1 ROW ONLY