MySQL按两列分组

时间:2013-11-29 11:57:09

标签: mysql

我有一张表格,列出订单的费用以及与订单相关的发票的ID。

orderID,financialType,invoiceID

我希望获得所有具有financialType ='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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

尝试:

  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

答案 2 :(得分:0)

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

演示
相关问题