如何优化sql中的子查询?

0kjbasz6  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(411)

我有一个数据集,列示例信息如下:

  1. Date ID Cost
  2. 05/01 1001 30
  3. 05/01 1024 19
  4. 05/01 1001 29
  5. 05/02 1001 28
  6. 05/02 1002 19
  7. 05/02 1008 16
  8. 05/03 1017 89
  9. 05/04 1003 28
  10. 05/04 1001 16
  11. 05/05 1017 28
  12. 05/06 1002 44
  13. ... etc...

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

  1. Date ID
  2. 05/01 1001
  3. 05/02 1001
  4. 05/03 1017
  5. 05/04 1003
  6. ...etc...

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

  1. select Date, ID
  2. from (select Date, ID, max(SumCost)
  3. from (select Date, ID, sum(cost) as SumCost
  4. from table1
  5. group by Date, ID) a
  6. group by Date, ID) b;

这看起来有点愚蠢,我想优化查询。关键是我只想输出日期和id,这两列。
有什么建议吗?

ttygqcqt

ttygqcqt1#

下面是一个使用相关子查询的方法:

  1. select t.*
  2. from t
  3. where t.cost = (select max(t2.cost) from t t2 where t2.date = t.date);
up9lanfz

up9lanfz2#

如果在同一天玩家有多个成本时,我们取一个最大成本,那么这个查询将起作用。您上面写的查询不正确。

  1. Select date, ID
  2. from
  3. (
  4. Select Date, ID, row_number() over(partition by date order by cost desc) as rnk
  5. from table
  6. ) a
  7. where rnk = 1

相关问题