我有一个包含以下列的表:
|customerNum|OrderNumber|ArticleNumber|PaymentType|Returned?|OrderDate |
|1 |1 |1 |cash |Yes |01.01.2016|
|2 |2 |3 |credit |No |30.02.2016|
|1 |1 |2 |cash |No |01.01.2016|
|2 |2 |4 |credit |Yes |30.02.2016|
|3 |3 |2 |credit |No |17.05.2016|
|2 |4 |8 |cash |Yes |19.08.2016|
预期结果:
customerNum|Numb.ofOrdersTot|ratioCash/CreditPayment|returnRate|LastOrder |
|1 |1 |1 |0,5 |01.01.2016|
|2 |2 |0.5 |0,66 |19.08.2016|
|3 |1 |0 |0 |17.05.2016|
我想计算每个客户的订单总数(非订购商品)(一个订单可以有多个商品),现金支付和信用支付的比率(现金支付数量/信用支付数量(一个)订单与多个商品具有相同的付款方式))客户的退货率(numberOfReturnedArticles / numberOfArticlesOrderedbycustomerTotal)和最后订单日期
我已经尝试了它的一部分,但这不起作用而且不完整:
`COUNT(*) AS Numb.ofOrdersTot,(COUNT(orderNumber)/COUNT(Returned? = Yes)) FROM table 1 group by customerNum;`
PLZ帮助我:非常重要:/
答案 0 :(得分:1)
这是我的答案。请检查它,看看字段是否正确类型。此外,我已添加2秒字段'orderdate2'与另一种格式。你可以删除一个。所以你的'预期结果'不能来自你的输入
SELECT
customerNum AS 'customerNum'
, SUM(1) AS 'Numb.ofOrdersTot'
, SUM(IF(`PaymentType` = 'credit',1,0)) / SUM(1) AS 'ratioCash/CreditPayment'
, SUM(IF(`Returned?` = 'Yes',1,0)) / SUM(1) AS 'returnRate'
,MAX(`OrderDate`) AS 'LastOrder'
,DATE_FORMAT(MAX(`OrderDate`),'%d.%m.%Y') AS 'LastOrder2'
FROM orders
GROUP BY customerNum;
<强>样品强>
mysql> SELECT * FROM orders;
+----+-------------+-------------+---------------+-------------+-----------+------------+
| id | customerNum | OrderNumber | ArticleNumber | PaymentType | Returned? | OrderDate |
+----+-------------+-------------+---------------+-------------+-----------+------------+
| 1 | 1 | 1 | 1 | cash | Yes | 2016-01-01 |
| 2 | 2 | 2 | 3 | credit | No | 2016-02-29 |
| 3 | 1 | 1 | 2 | cash | No | 2016-01-01 |
| 4 | 2 | 2 | 4 | credit | Yes | 2016-02-29 |
| 5 | 3 | 3 | 2 | credit | No | 2016-05-17 |
| 6 | 2 | 4 | 8 | cash | Yes | 2016-08-19 |
+----+-------------+-------------+---------------+-------------+-----------+------------+
6 rows in set (0,00 sec)
mysql> SELECT
-> customerNum AS 'customerNum'
-> , SUM(1) AS 'Numb.ofOrdersTot'
-> , SUM(IF(`PaymentType` = 'credit',1,0)) / SUM(1) AS 'ratioCash/CreditPayment'
-> , SUM(IF(`Returned?` = 'Yes',1,0)) / SUM(1) AS 'returnRate'
-> ,MAX(`OrderDate`) AS 'LastOrder'
-> ,DATE_FORMAT(MAX(`OrderDate`),'%d.%m.%Y') AS 'LastOrder2'
-> FROM orders
-> GROUP BY customerNum;
+-------------+------------------+-------------------------+------------+------------+------------+
| customerNum | Numb.ofOrdersTot | ratioCash/CreditPayment | returnRate | LastOrder | LastOrder2 |
+-------------+------------------+-------------------------+------------+------------+------------+
| 1 | 2 | 0.0000 | 0.5000 | 2016-01-01 | 01.01.2016 |
| 2 | 3 | 0.6667 | 0.6667 | 2016-08-19 | 19.08.2016 |
| 3 | 1 | 1.0000 | 0.0000 | 2016-05-17 | 17.05.2016 |
+-------------+------------------+-------------------------+------------+------------+------------+
3 rows in set (0,00 sec)
mysql>