0

我需要显示当前年份和上一年迄今为止的结果。理想情况下,我希望结果看起来像

ID|CYTD|PYTD
# |Sum |Sum

我的查询如下所示。问题是我如何设置与当年的行匹配相同的 id 的位置。

select Table.ID,
 SUM(Table.Column) as CYTD, 

(select SUM(Table.Column) from Table
where Table.Id = ?? and Table.Year between Prev and Current
group by Table.Id) as PYTD

Where Table.Year between Current and Future
group by Table.Id
4

1 回答 1

0

尝试以下方式:

SELECT TT.ID,
    SUM(TT.amount) AS CYTD,
    (SELECT SUM(T.amount)
     FROM YOURTABLE T
     WHERE T.Id = TT.id
        AND T.DATE BETWEEN '2012-01-01' AND '2013-01-01'
     GROUP BY T.Id) AS PYTD
FROM YOURTABLE TT
WHERE TT.DATE BETWEEN '2013-01-01' AND '2014-01-01'
GROUP BY TT.Id

因为yourtable在查询中出现了不止一次,所以你必须在每次出现时给它一个别名,然后你比较它们的 id,这应该给出你想要的结果。

编辑:

如果您希望它是动态的,并使用当前年份作为参考,您可以这样做:

SELECT TT.ID,
    SUM(TT.amount) AS CYTD,
    (SELECT SUM(T.amount)
     FROM YOURTABLE T
     WHERE T.Id = TT.id
        AND YEAR(T.DATE) = YEAR(now())
     GROUP BY T.Id) AS PYTD
FROM YOURTABLE TT
WHERE YEAR(TT.DATE) = YEAR(now()) - 1
GROUP BY TT.Id;

看看这个小提琴看看它在行动。

于 2013-08-02T19:30:47.893 回答