简体   繁体   中英

Rewrite query to use window functions except CTE's and subqueries

I have 2 related tables.

package :

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

sort :

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

I need to calculate percentage of volume of certain sort over total volume filtered by sort.id_standard . There is full query with CTE's

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;

I'm sure, window functions will do the best there, but has no experience with them in real life.

No need to use window function here, something like this should help

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM