在不使用 Union ALL 的情况下添加多个 select 语句

Adding multiple select statements without using Union ALL

我目前编写了一个查询,该查询使用 UNION ALL 和 returns 添加多个 select 语句,每个 select 语句中的金额总和。我的问题:是否有任何方法或方法可以使此查询更小(不是那么冗长)?

每个子查询中唯一改变的是用于从帐户中获取 ID1 的 ID# Table

 SELECT SUM(TOTAL) TOTAL
 FROM
(
SELECT ISNULL (round(sum(signeddata),2),0)
FROM BUDGET
WHERE CATEGORY = 'ACTL'
AND TIME BETWEEN '20210100' AND '20210800'
AND CURRENCY = 'DOL'
AND DATASRC IN (
    SELECT ID1 FROM DataSrc
    WHERE ID7 = 'Logic')
AND ACCOUNT IN (
    select ID1 from Accnt
    where ID7 = 'EXPENSES')
AND ENTITY IN (
    SELECT ID1 FROM Entity
    where ID9 = 'H2')

UNION ALL

SELECT ISNULL (round(sum(signeddata),2),0)*-1
FROM BUDGET
WHERE CATEGORY = 'ACTL'
AND TIME BETWEEN '20210100' AND '20210800'
AND CURRENCY = 'DOL'
AND DATASRC IN (
    SELECT ID1 FROM DataSrc
    WHERE ID7 = 'Logic')
AND ACCOUNT IN (
    select ID1 from Accnt
    where ID7 = 'MERC')
AND ENTITY IN (
    SELECT ID1 FROM Entity
    where ID9 = 'H2')

    UNION ALL

SELECT ISNULL (round(sum(signeddata),2),0)*-1
FROM BUDGET
WHERE CATEGORY = 'ACTL'
AND TIME BETWEEN '20210100' AND '20210800'
AND CURRENCY = 'DOL'
AND DATASRC IN (
    SELECT ID1 FROM DataSrc
    WHERE ID7 = 'Logic')
AND ACCOUNT IN (
    select ID1 from Accnt
    where ID11 = 'SYNP')
AND ENTITY IN (
    SELECT ID1 FROM Entity
    where ID9 = 'H2')
) S

一个想法是对 case-semijoins 求和而不是将它们放在 FROM 子句中:

SELECT 
    ISNULL(round(sum(signeddata),2),0)
    *
    (
        case when ACCOUNT IN (select ID1 from Accnt where ID7 = 'EXPENSES') 
        then 1 else 0 end * 1
        +
        case when ACCOUNT IN (select ID1 from Accnt where ID7 = 'MERC') 
        then 1 else 0 end * (-1)
        +
        case when ACCOUNT IN (select ID1 from Accnt where ID7 = 'SYNP') 
        then 1 else 0 end * (-1)
    )
FROM BUDGET
WHERE CATEGORY = 'ACTL'
AND TIME BETWEEN '20210100' AND '20210800'
AND CURRENCY = 'DOL'
AND DATASRC IN (
    SELECT ID1 FROM DataSrc
    WHERE ID7 = 'Logic')
AND ENTITY IN (
    SELECT ID1 FROM Entity
    where ID9 = 'H2')

您可以只使用 IN 作为 ID7

Always specify table references for columns, especially on correlated subqueries

SELECT
  ISNULL(round(sum(b.signeddata), 2), 0) TOTAL
FROM BUDGET b
WHERE b.CATEGORY = 'ACTL'
  AND b.TIME BETWEEN '20210100' AND '20210800'
  AND b.CURRENCY = 'DOL'
  AND b.DATASRC IN (
      SELECT ds.ID1 FROM DataSrc ds
      WHERE ds.ID7 = 'Logic')
  AND b.ACCOUNT IN (
      select a.ID1 from Accnt a
      where a.ID7 IN ('EXPENSES', 'MERC', 'SYNP'))
  AND b.ENTITY IN (
      SELECT e.ID1 FROM Entity e
      where e.ID9 = 'H2');

请注意,如果您这样做,舍入会略有不同