计算总计数的百分比

时间:2018-01-15 08:32:38

标签: sql tsql

早上好

好的,所以我知道如何使用像。

来获得百分比
ROUND(CAST(SUM(Col1)AS FLOAT)  *100.0 / COUNT(*),2)

但这就是我被困的地方。

DECLARE @pYWK INT
SET @pYWK = (SELECT YWK FROM CHDS_Management.dbo.Calendar 
          WHERE DT = (SELECT DATEADD(WEEK,-3, CONVERT(DATE,GETDATE()))));

SELECT
    ORD.ProductWhsLocation AS 'Location', 
    COUNT(ORD.ProductWhsLocation) AS 'Picked'
FROM CHDS_Common.dbo.OMOrder AS ORD
    INNER JOIN CHDS_Management.dbo.PickZoneControl AS PZC ON 
LEFT(ORD.ProductWhsLocation,3) = PZC.PickZone
    INNER JOIN CHDS_Management.dbo.Calendar AS CAL ON CAL.DT = 
ORD.EarliestPickDate
WHERE CAL.YWK = @pYWK AND ORD.PickedQty <> 0
GROUP BY ORD.ProductWhsLocation

我想要解决的是从每个选择中挑选出来的百分比。

它的星期一早上在这里,如果我失踪了它的蠢事,我很抱歉。

感谢您对此提供任何帮助。

2 个答案:

答案 0 :(得分:1)

这是一个棘手的问题,因为要获得每个组的百分比(需要一个聚合),我们需要使用整个查询的总计数(另一个聚合)来规范化这些计数。一种方法是将基本连接查询放入CTE。然后,查询CTE并通过同一CTE上的子查询获取总计数。

WITH cte AS (
    SELECT
        ORD.ProductWhsLocation AS 'Location'
    FROM CHDS_Common.dbo.OMOrder AS ORD
    INNER JOIN CHDS_Management.dbo.PickZoneControl AS PZC
        ON LEFT(ORD.ProductWhsLocation,3) = PZC.PickZone
    INNER JOIN CHDS_Management.dbo.Calendar AS CAL
        ON CAL.DT = ORD.EarliestPickDate
    WHERE CAL.YWK = @pYWK AND ORD.PickedQty <> 0
)

SELECT
    Location,
    COUNT(Location),
    ROUND(100.0 * COUNT(Location) / (SELECT COUNT(*) FROM cte), 2) AS pct
FROM cte
GROUP BY
    Location;

答案 1 :(得分:0)

使用Count(*)Over()获取位置总数,用它来划分Picked以获取每个位置的挑选百分比

SELECT ORD.ProductWhsLocation        AS 'Location',
       Count(ORD.ProductWhsLocation) AS 'Picked',
       ( ( Count(ORD.ProductWhsLocation) * 1.0 ) / Sum(Count(ORD.ProductWhsLocation)) OVER() ) * 100.0
FROM   CHDS_Common.dbo.OMOrder AS ORD
       INNER JOIN CHDS_Management.dbo.PickZoneControl AS PZC
               ON LEFT(ORD.ProductWhsLocation, 3) = PZC.PickZone
       INNER JOIN CHDS_Management.dbo.Calendar AS CAL
               ON CAL.DT = ORD.EarliestPickDate
WHERE  CAL.YWK = @pYWK
       AND ORD.PickedQty <> 0
GROUP  BY ORD.ProductWhsLocation