【问题标题】:Returning rows that have more than one unique value in a column返回列中具有多个唯一值的行
【发布时间】:2021-08-18 13:09:16
【问题描述】:
select customer_id, currency, price
from sales_table

customer_id   currency  price
1001            CHF       50
1001            EUR       35
1002            EUR       40
1003            AUD       25

我的表中有数十万笔交易。 如何执行仅返回以两种不同货币付款的客户的选择子句? 在这种情况下,select 语句应该返回 customer_id 1001。

【问题讨论】:

  • 考虑使用having子句,但不知道如何从那里移开
  • GROUP BY, HAVING count(distinct currency) > 1
  • 在这种情况下,为什么要计算 distinct 而不是 count(currency)?
  • 你需要 DISTINCT 因为否则如果你只是用欧元支付 2 次,也会显示出来
  • 您可以将行 (1003, AUD, 10) 添加到您的样本数据中,以改进它,并确保更好的质量答案。

标签: sql postgresql


【解决方案1】:
select customer_id
from sales_table
group by customer_id
HAVING count(distinct currency) = 2 // or >1 or whatever

【讨论】:

    【解决方案2】:
    select customer_id
    from
    (
        select customer_id, currency
        from sales_table
        group by customer_id, currency
    ) t
    group by customer_id
    having count(customer_id) > 1;
    

    你可以测试一下here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多