建议一个简单的SQL查询

时间:2015-09-11 17:02:38

标签: sql db2

我有下表:

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”,我需要返回具有最高“final_score”的“product_B”。 例如,如果我检查NY“state”,“product_A”Blackberry,我希望我的查询返回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

我上面提到的查询给了我想要的输出。但是,我知道连接会增加查询的复杂性。有人可以用更简单的查询建议另一种方法吗?

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

您需要先计算maxScore。然后加入两个表来获取名称。

<强> SQL Fiddle Demo 这使用sql server cte,MySql需要内部选择。

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