计算使用TOP子句的两列之间的百分比

时间:2017-10-15 07:21:32

标签: sql-server tsql

我在SQL Server中编写存储过程,执行以下操作:

  1. 获取前5名导入者
  2. 计算每个
  3. 的进口值和进口量之和
  4. 根据总进口总值和总量计算百分比
  5. 这是我的疑问:

        DECLARE @OVERALL_TOTAL_VAL AS BIGINT
        DECLARE @OVERALL_TOTAL_VOL AS BIGINT
    
        SET NOCOUNT ON;
    
        -- GET TOTAL VALUE AND VOLUME FROM ALL IMPORTERS TO USE FOR GETTING THE %
        SET @OVERALL_TOTAL_VAL = (SELECT SUM(IMPORTEDVALUE) 
                                    FROM [DBO].[ALERT]
                                    WHERE IMPORTERCODE != 0)
        SET @OVERALL_TOTAL_VOL = (SELECT SUM(IMPORTEDVOLUME)
                                    FROM [DBO].[Alert]
                                    WHERE IMPORTERCODE != 0)
    
        -- GET TOP 5 IMPORTERS
        SELECT 
            TOP 5 IMPORTERCODE,
            @OVERALL_TOTAL_VAL TOTAL_VAL,
            @OVERALL_TOTAL_VOL TOTAL_VOL,
            SUM(IMPORTEDVALUE) TOTAL_IMPORT_VALUE, 
            SUM(IMPORTEDVOLUME) TOTAL_IMPORT_VOL, 
            --((SUM(IMPORTEDVALUE) / @OVERALL_TOTAL_VAL) * 100) NET_VAL,
            --((SUM(IMPORTEDVOLUME) / @OVERALL_TOTAL_VOL) * 100) NET_VOL,
            --(((SELECT SUM(IMPORTEDVALUE) 
            -- FROM [DBO].[ALERT]
            -- WHERE IMPORTERCODE = A1.IMPORTERCODE
            -- GROUP BY IMPORTERCODE) / @OVERALL_TOTAL_VAL) * 100 ) NET_VAL,
            COUNT(*) ALERT_COUNT
        FROM [DBO].[ALERT] A1
    
        WHERE IMPORTERCODE != 0
        GROUP BY IMPORTERCODE
        ORDER BY ALERT_COUNT DESC;
    

    评论出来的是我尝试过的,但不幸的是没有用。我也尝试过交叉加入(通过Get column sum and use to calculate percent of total (mySQL));也不行。

    这是因为我的TOP 5声明中有SELECT吗?我试图做的是什么?因为如果没有,我必须在我的应用程序的前端进行百分比计算,如果可能的话我想避免这种情况。

    请帮忙。谢谢。

    更新:最后让它发挥作用。猜猜毕竟不需要参数。谢谢lad2025的帮助!

    SELECT DISTINCT
        TOP 5 IMPORTERCODE,
        SUM(IMPORTEDVALUE) OVER(PARTITION BY IMPORTERCODE) AS TOTAL_IMPORT_VAL,
        SUM(IMPORTEDVOLUME) OVER(PARTITION BY IMPORTERCODE) AS TOTAL_IMPORT_VOL,
        100.0 * SUM(IMPORTEDVALUE) OVER (PARTITION BY IMPORTERCODE)/
                SUM(IMPORTEDVALUE) OVER() AS NET_VAL,
        100.0 * SUM(IMPORTEDVOLUME) OVER (PARTITION BY IMPORTERCODE)/
                SUM(IMPORTEDVOLUME) OVER() AS NET_VOL,
        COUNT(*) OVER(PARTITION BY IMPORTERCODE) ALERT_COUNT
    FROM [DBO].[ALERT]
    WHERE IMPORTERCODE != 0
    ORDER BY ALERT_COUNT DESC;
    

1 个答案:

答案 0 :(得分:2)

您可以使用windowed functions

SELECT DISTINCT TOP 5 IMPORTERCODE,
   SUM(IMPORTEDVALUE) OVER(PARTIITON BY IMPORTERCODE) AS total_import_value
   SUM(IMPORTEDVOLUME) OVER(PARTIITON BY IMPORTERCODE) AS total_import_volumne,
   100.0 * SUM(IMPORTEDVALUE) OVER(PARTIITON BY IMPORTERCODE)/
           SUM(IMPORTEDVALUE) OVER() AS [% value percentage],
   100.0 * SUM(IMPORTEDVOLUME) OVER(PARTIITON BY IMPORTERCODE)/
           SUM(IMPORTEDVOLUME) AS [% volume percentage]
FROM [DBO].[ALERT]
WHERE IMPORTERCODE != 0
ORDER BY total_import_value DESC