【问题标题】:Redshift SQL query help needed需要 Redshift SQL 查询帮助
【发布时间】:2017-03-18 19:41:03
【问题描述】:

order_details:

order_id   dish_id     category_id
----------------------------------
   601        22            123
   601        23            234
   603        32            456
   603        54            456
   603        11            543
   603        19            456

从上面提供的示例表中:我如何根据每个order_id 的不同组对order_id,dish_idcategory_id 进行分组?

结果应该是这样的

order_id   dish_id     category_id     count
---------------------------------------------
   601        22            123          1
   601        23            234          1
   603        32            456          3
   603        54            452          3
   603        11            543          3
   603        19            456          3

注意:

就像order_id 601 中的dish_id 22 和1 个不同的不同category_id234 一样,同样在order_id 603 dish_id 32 中也有2 个不同的不同category_id456, 543

【问题讨论】:

  • 我删除了不兼容的数据库标签。另外,你的数字没有意义。为什么 603 的值是“2”而不是“3”?
  • 抱歉打错了,我的错,谢谢指出

标签: sql amazon-redshift


【解决方案1】:

如果我假设三元组是唯一的,那么您似乎希望比组数少 1。那将是:

select t.*,
       (count(*) over (partition by order_id) - 1) as cnt
from t;

【讨论】:

  • 感谢@Gordon Linoff,它非常适合提供的数据集,但是如果我在结果表中再插入一列,例如“603、02、543”,那么现在不同 category_id 的计数为 4 ,这是正确的,因为 category_id 543 已准备好出现在 order_id 603 中,计数仍应为 3 我该如何在上述查询中提前完成
  • count(distinct category_id) 在 Redshift 中工作吗?
  • 不,先生,它在执行时没有让我出错
  • @GordonLinoff: count(distinct category_id) 在 Redshift 中工作。
  • @ankitkhanduri:请告诉我们您遇到了什么错误。这可能是由于你的错误。
猜你喜欢
  • 2011-04-03
  • 1970-01-01
  • 2016-07-04
  • 2016-07-26
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 2011-03-14
  • 1970-01-01
相关资源
最近更新 更多