如何从单个表中的数据计算两个特定期间的收入差异?

mefy6pfw  于 2021-07-26  发布在  Java
关注(0)|答案(4)|浏览(256)

我使用的是sql server 2014,我有下面的t-sql查询,它应该计算基于两个特定期间的总收入差异。执行计算的数据来自一个sql表。
总而言之,我在表中有一列 T1 打电话 Revenue 另一个专栏叫 Month . 我需要找出2020年9月至2020年12月与2019年9月至2019年12月的收入差异。
我的t-sql查询如下:

USE [MyDatabase]

;with cte1 as 
(
  SELECT 
    sum ([Revenue]) as 'Revenue Sep 19 - Dec 19'
  FROM
    [T1]
  WHERE
    [Month] between '2019-09-01' and '2019-12-01'
),
cte2 as (
  SELECT
    sum ([Revenue]) as 'Revenue Sep 20 - Dec 20'
  FROM
    [T1]
  WHERE
    [Month] between '2020-09-01' and '2020-12-01'
),
cte3 as (
  SELECT 
    cte2.[Revenue Sep 20 - Dec 20] as 'Total Revenue',
    'Sep 20 - Dec 20' as 'Period',
    '1' as 'ID'
  FROM
    [cte2]

  UNION ALL 

  SELECT 
    cte1.[Revenue Sep 19 - Dec 19] as 'Total Revenue',
    'Sep 19 - Dec 19' as 'Period',
    '1' as 'ID'
  FROM
    [cte1]
)
select a.[Total Revenue] - b.[Total Revenue]
from
  (select cte3.[Total Revenue] from [cte3] where cte3.[Period] = 'Sep 20 - Dec 20') a
  JOIN
  (select cte3.[Total Revenue] from [cte3] where cte3.[Period] = 'Sep 19 - Dec 19') b
  ON b.[ID] = a.[ID]

我的查询基于以下内容:如何在同一表的不同行组之间进行计算
但是,在运行查询时,我收到以下错误消息:
列名“id”无效。
我不知道我在这里做错了什么。不是列吗 ID 出现在 cte3 ?

30byixjq

30byixjq1#

ID 必须出现在两者的选择列表中 a 以及 b 为了让公众能看到它 join :

from
  (select cte3.ID, cte3.[Total Revenue] from [cte3] where cte3.[Period] = 'Sep 20 - Dec 20') a
  JOIN
  (select cte3.ID, cte3.[Total Revenue] from [cte3] where cte3.[Period] = 'Sep 19 - Dec 19') b
  ON b.[ID] = a.[ID]
b1zrtrql

b1zrtrql2#

你的查询比必要的复杂多了。

SELECT (SUM(CASE WHEN [Month] between '2020-09-01' and '2020-12-01' THEN [Revenue] ELSE 0 END) -
        SUM(CASE WHEN [Month] between '2019-09-01' and '2019-12-01' THEN [Revenue] ELSE 0 END)
       ) as difference
FROM [T1];

你的版本有三个CTE,一个 UNION ALL ,两个子查询和 JOIN .
笔记:
不要使用单引号分隔列别名。字符串和日期只能使用单引号。
为列命名别名,这样就不需要转义。例如,使用下划线而不是空格。
不要使用无意义的表别名,例如 a 以及 b . 使用有意义的词,例如 t2019 .

1dkrff03

1dkrff033#

使用时 SUB QUERY 您还必须提到您在连接条件中提到的列

SELECT A.[TOTAL REVENUE] - B.[TOTAL REVENUE]
FROM
(SELECT CTE3.[TOTAL REVENUE],CTE3.ID FROM [CTE3] WHERE CTE3.[PERIOD] = 'SEP 20 - DEC 20') A
JOIN
(SELECT CTE3.[TOTAL REVENUE],CTE3.ID FROM [CTE3] WHERE CTE3.[PERIOD] = 'SEP 19 - DEC 19') B ON B.[ID] = A.[ID]
fcipmucu

fcipmucu4#

尝试下面的代码,它将帮助你

USE [MyDatabase]

select sum([Revenue Sep 20 - Dec 20])-sum([Revenue Sep 19 - Dec 19]) as revenue_diffrence 
from
(
SELECT 
    [Revenue] as 'Revenue Sep 19 - Dec 19', 0 as 'Revenue Sep 20 - Dec 20'
  FROM
    [T1]
  WHERE
    [Month] between '2019-09-01' and '2019-12-01'

union all
SELECT
    0 as 'Revenue Sep 19 - Dec 19',[Revenue] as 'Revenue Sep 20 - Dec 20'
  FROM
    [T1]
  WHERE
    [Month] between '2020-09-01' and '2020-12-01'
)a

相关问题