我正在尝试根据代码的CASES部分中提到的三种不同情况来计算订单百分比。当我运行代码时,每种情况下的值都将百分比值显示为“ 1”。我认为问题出在代码的最后一行,我该如何解决?
SELECT DATEDIFF_GRP,ROUND(COUNT(DISTINCT(ORDER_ID))*100/(SELECT COUNT(DISTINCT(A.ORDER_ID)) FROM A),2)||'%' AS PERCENTAGE_ORDERS FROM A
GROUP BY DATEDIFF_GRP ;
答案 0 :(得分:1)
MySQL通常不使用||
进行字符串连接,您必须启用一些非默认选项才能实现此功能。
正在发生的事情是MySQL相反将||
解释为逻辑OR
运算符。为完全避免此问题,请考虑使用CONCAT
函数。
SELECT
DATEDIFF_GRP,
CONCAT(100 * ROUND(COUNT(DISTINCT(ORDER_ID)) /
(SELECT COUNT(DISTINCT(A.ORDER_ID)) FROM A), 2), '%') AS PERCENTAGE_ORDERS
FROM A;
您可以还可以通过启用ANSI
模式来解决您的问题,但是正如下面所评论的,很少有MySQL用户在此模式下使用数据库。
答案 1 :(得分:0)
您可以在下面尝试-在我看来,您尝试使用||
运算符进行连接,但是mysql支持concat()
函数而不是||
运算符
WITH A AS (SELECT OS.ACTUAL_DISPATCH_DATE,OT.ORDER_ID,OT.First_msg_date,datediff(OT.First_msg_date,OS.ACTUAL_DISPATCH_DATE) AS DATEDIFF,
CASE WHEN datediff(OT.First_msg_date,OS.ACTUAL_DISPATCH_DATE)<=0 THEN 'OTIF'
WHEN datediff(OT.First_msg_date,OS.ACTUAL_DISPATCH_DATE)=1 THEN 'OTIF+1'
WHEN datediff(OT.First_msg_date,OS.ACTUAL_DISPATCH_DATE)=2 THEN 'OTIF+2'
ELSE 'OTIF+>2'
END as DATEDIFF_GRP
FROM order_shipment OS RIGHT JOIN
(SELECT ORDER_ID,MIN((str_to_date(SUBSTRING(MESSAGE,INSTR(MESSAGE,'2'),10),'%Y-%m-%d'))) AS First_msg_date
FROM ORDER_TIMELINE
GROUP BY ORDER_ID ) OT
ON (OS.ORDER_ID=OT.ORDER_ID))
SELECT DATEDIFF_GRP,concat(ROUND(COUNT(DISTINCT(ORDER_ID))*100/(SELECT COUNT(DISTINCT(A.ORDER_ID)) FROM A),2),'%') AS PERCENTAGE_ORDERS
FROM A
GROUP BY DATEDIFF_GRP ;