我在SQL Server中遇到问题,我不知道如何修复。从下面的查询和输出我需要生成以下度量:大小级别的ATP(可承诺)百分比,即:
有3种尺寸,2种有qtys - 1种没有。如果有任何数量,那么我想返回值' 1'如果不是' 0' (CASE声明)
留下2的值为' 1'和#0;' 0 (2/3)或66%'全尺寸ATP'
如何使用下面的查询生成该计算?我在COUNT
声明中尝试了CASE
但没有运气。
感谢帮助。
查询:
SELECT A.MATERIAL,
M.SIZE_LITERAL,
DATEPART(mm,AVAIL_DATE) AS 'MONTH',
CASE
WHEN A.AVAIL_QTY IS NULL
THEN '0'
ELSE A.AVAIL_QTY
END AS 'AVAIL_QTY',
COUNT(AVAIL_QTY) AS 'COUNT_ATP_QTY',
COUNT(AVAIL_QTY)/COUNT(*) AS 'ATP %'
FROM VW_MM_SALES_GRID M LEFT OUTER JOIN VW_ATP_DOWNLOAD_NOREQCAT A
ON A.MATERIAL = M.MATERIAL
AND A.SIZE_LITERAL = M.SIZE_LITERAL
AND A.STOCK_CATEGORY IN ('A60381000','A60382000')
AND A.AVAIL_DATE BETWEEN GETDATE() AND GETDATE() + 90
WHERE M.MATERIAL = 'AA2721' AND M.ACTIVE_FLAG IS NOT NULL
GROUP BY A.MATERIAL,
M.SIZE_LITERAL,
AVAIL_DATE,
A.AVAIL_QTY,
A.STOCK_CATEGORY
SELECT @@ROWCOUNT
结果:
MATERIAL SIZE_LITERAL MONTH AVAIL_QTY COUNT_ATP_QTY ATP %
------------------ ------------ ----------- --------------------------------------- ------------- -----------
NULL S NULL 0 0 0
AA2721 L 8 45 1 1
AA2721 M 8 51 1 1
Warning: Null value is eliminated by an aggregate or other SET operation.
(3 row(s) affected)
-----------
3
(1 row(s) affected)
答案 0 :(得分:0)
这应该这样做 - 你需要在结果中为每个材料获得一行,因为你正在计算聚合(ATP),并且NULL不会被计算,所以你不需要使用CASE,你可以算一下非NULL并除以总计数。
SELECT COUNT(NULLIF(A.AVAIL_QTY, 0)) / COUNT(*) * 100 AS [Full Size ATP]
FROM VW_MM_SALES_GRID M LEFT OUTER JOIN VW_ATP_DOWNLOAD_NOREQCAT A
ON A.MATERIAL = M.MATERIAL
AND A.SIZE_LITERAL = M.SIZE_LITERAL
AND A.STOCK_CATEGORY IN ('A60381000','A60382000')
AND A.AVAIL_DATE BETWEEN GETDATE() AND GETDATE() + 90
WHERE M.MATERIAL = 'AA2721' AND M.ACTIVE_FLAG IS NOT NULL