重写查询以使用除CTE和子查询之外的窗口函数

时间:2018-01-22 06:24:46

标签: sql sql-server-2012 window-functions

我有2张相关的表格。

package

| id_sort | volume | date |
---------------------------
| int     | float  | date |

sort

| id  | id_standard |
---------------------
| int | int         |

我需要计算特定种类的音量百分比超过sort.id_standard过滤的总音量。 CTE的完整查询

WITH total(volume) AS (
    SELECT SUM(package.volume) as volume
    FROM package
    LEFT JOIN sort ON sort.id = package.id_sort
    WHERE
        sort.id_standard IN (2,3)
        AND package.date >= CONVERT(VARCHAR(7), GETDATE(), 120) + '-01 08:00:00' -- Start of current month
        AND package.id_conv <> 12 -- additional filter
), filtered(volume) AS (
    SELECT SUM(package.volume) as volume
    FROM package
    WHERE package.id_sort = 17
        AND package.date >= CONVERT(VARCHAR(7), GETDATE(), 120) + '-01 08:00:00' -- start of current month
        AND package.id_conv <> 12 -- additional filter
)
SELECT CAST((filtered.volume * 100 / total.volume) AS NUMERIC(3,2)) [percentage] FROM total, filtered;

我敢肯定,窗口功能会在那里做到最好,但在现实生活中没有经验。

1 个答案:

答案 0 :(得分:1)

这里不需要使用window功能,这样的事情应该有帮助

SELECT [percentage] = Cast(( volume * 100 / Nullif(volume,0) ) AS NUMERIC(3, 2))
FROM   (SELECT total = Sum(volume),
               volume = Sum(CASE WHEN p.id_sort = 17 THEN p.volume ELSE 0 END)
        FROM   package p
               LEFT JOIN sort s
                      ON s.id = p.id_sort
                         AND sort.id_standard IN ( 2, 3 )
        WHERE  p.date >= CONVERT(VARCHAR(7), Getdate(), 120)
                         + '-01 08:00:00' -- Start of current month
               AND p.id_conv <> 12)a