如何在SQL中优化子查询?

时间:2018-04-18 06:38:43

标签: mysql sql

我有一个数据集,列样本信息如下:

Date     ID     Cost
05/01   1001     30
05/01   1024     19
05/01   1001     29
05/02   1001     28
05/02   1002     19
05/02   1008     16
05/03   1017     89
05/04   1003     28
05/04   1001     16
05/05   1017     28
05/06   1002     44
... etc...

我想创建一个表来显示每天最顶层的付款人(成本最高),这意味着表中只有两列,输出样本应该是这样的:

Date      ID
05/01    1001
05/02    1001
05/03    1017
05/04    1003
...etc...

我知道这个问题很简单,我的问题是我想简化查询。

我的查询:

select Date, ID
from (select Date, ID, max(SumCost)
      from (select Date, ID, sum(cost) as SumCost
            from table1
            group by Date, ID) a
      group by Date, ID) b;

这似乎有点愚蠢,我想优化查询。关键是我只想输出Date和Id,这两列。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

以下是使用相关子查询的方法:

select t.*
from t
where t.cost = (select max(t2.cost) from t t2 where t2.date = t.date);

答案 1 :(得分:0)

如果我们在同一天玩家有多个费用时采取最高费用,那么此查询将有效。您在上面写的查询不正确。

Select date, ID
from
(
Select Date, ID, row_number() over(partition by date order by cost desc) as rnk
from table
) a
where rnk = 1