嵌套选择动态在哪里

时间:2013-08-02 15:02:53

标签: sql select nested sum

我需要显示当前年度和上一年度的结果。理想情况下,我希望结果看起来像是

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

1 个答案:

答案 0 :(得分: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;

请参阅此fiddle以查看其实际效果。