【问题标题】:MySQL grouping by two columnsMySQL按两列分组
【发布时间】:2013-11-29 20:10:40
【问题描述】:

我有一个表格,其中列出了针对订单的费用以及与订单关联的发票 ID。

orderID、financialType、invoiceID

我希望获取所有具有 financeType='17' 但具有不同 invoiceID 的订单

示例表:

orderID     financialType       invoiceID
123000      10                  NULL
123000      17                  900
123000      17                  901
123111      17                  902
123111      17                  902
123222      10                  NULL
123333      17                  900
123444      17                  900
123444      17                  901
123444      17                  902

在这种情况下,我对 123000(开 2 张不同发票)和 123444(开 3 次发票)感兴趣。

我目前的查询是:

SELECT orderID, count(*) as freq FROM orders WHERE financialType='17' group by orderID, invoiceID having freq > 1 order by freq desc

但这是给我每个订单的总收费次数,而不是在不同发票上收费的次数。在我的示例中,我不关心 123111 - 这被收取了两次费用,但在同一张发票上,这很好。

我希望看到:

orderID  freq
123000  2
123444  3

【问题讨论】:

  • 显示您的预期输出。
  • @edper 我在上面添加了我的预期输出
  • select orderID, count(distinct invoiceID) 可以吗?
  • @user1281385 是的 - 这完美地完成了工作!
  • @user1698575 你不能在别名中使用。请参阅下面的答案。

标签: mysql


【解决方案1】:

此查询有效:

SELECT orderID, GROUP_CONCAT(invoiceID), count(DISTINCT invoiceID) as freq 
FROM orders 
WHERE financialType='17' 
group by orderID 
having freq > 1
order by freq desc

http://sqlfiddle.com/#!2/c2cc07/6

【讨论】:

    【解决方案2】:
    SELECT 
    count(orderID) as freq, orderID , invoiceID 
    FROM orders  
    WHERE financialType='17' 
    group by orderID 
    having freq > 1 
    order by orderID desc
    

    http://sqlfiddle.com/#!2/794ff/5 上的演示

    使用

    SELECT 
    count(orderID) as freq, orderID , GROUP_CONCAT(invoiceID) as invoiceIDs 
    FROM orders 
    WHERE financialType='17' 
    group by orderID 
    having freq > 1 
    order by orderID desc
    

    如果您还想查看订单的所有发票 ID

    http://sqlfiddle.com/#!2/794ff/9的演示

    【讨论】:

      【解决方案3】:

      试试:

        SELECT orderID, count(*) as freq 
        FROM orders WHERE financialType='17'
        GROUP BY orderid
        HAVING count(*)>1
      

      或者如果您想要一张独特的发票:

        SELECT orderID, count(DISTINCT invoiceID) as freq 
        FROM orders WHERE financialType='17'
        GROUP BY orderid
        HAVING count(*)>1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-04
        • 2022-11-21
        • 1970-01-01
        • 2016-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多