繁体   English   中英

MySQL按两列分组

[英]MySQL grouping by two columns

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

订单ID,财务类型,发票ID

我正在寻找所有具有financialType = '17'但具有不同的发票ID的订单

表格示例:

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

该查询有效:

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

尝试:

  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
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上进行演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM