减少查询中重复SUM函数的数量

时间:2017-04-08 10:19:27

标签: sql sql-server tsql

如何减少查询中SUM函数的数量?

    SELECT P_NAME "Product name", (SUM(case when PR = 1 then QUANTITY end) -
SUM(case when PR = 2 then QUANTITY end)) "End balance",
CAST((SUM(case when PR = 1 then QUANTITY*PRICE end) - SUM(case when PR = 2 then
QUANTITY*PRICE end)) as decimal(13,2)) "End balance" FROM RPOD, DMS, DMZ
WHERE RPOD.KTOV=DMS.KTOV AND DMZ.NDM=DMS.DMZ_FK
GROUP BY P_NAME
ORDER BY P_NAME;

1 个答案:

答案 0 :(得分:2)

您可以将它们组合在一起:

SELECT P_NAME as "Product name",
       SUM(case when PR = 1 then QUANTITY
                when PR = 2 then - QUANTITY
           end) as "End balance",
       SUM(case when PR = 1 then QUANTITY * PRICE
                when PR = 2 then - QUANTITY * PRICE
           end) as "End balance/price",
FROM RPOD JOIN
     DMS
     ON RPOD.KTOV = DMS.KTOV JOIN
     DMZ
     ON DMZ.NDM = DMS.DMZ_FK
GROUP BY P_NAME
ORDER BY P_NAME;

关于SUM() s更为重要的美学是学习使用正确的,明确的JOIN语法。 从不JOIN子句中使用逗号。此外,您不应在结果集中为两列指定相同的名称。