我正在寻找我的SQL问题的解决方案,我必须连续显示具有适当标题的财务期间的三个总计,到目前为止,我已显示所有信息,但它在使用union的列中。我不知道在哪里放置连接或哪种类型更适合,我真的很感激这个答案的帮助,因为我已经看了一段时间。
SELECT
(SELECT SUM(ComStatinYearTotal)
FROM tblComStatInYear
WHERE ComStatinYearYear = '2014'
AND ComStatInYearWeekEnd > '2014-07-01'
AND ComStatInYearWeekEnd < '2014-09-30'
AND ComStatInYearCltCode = 'STI02')
- (SELECT SUM(ComStatinYearTotal)
FROM tblComStatInYear
WHERE ComStatinYearYear = '2013'
AND ComStatInYearWeekEnd > '2013-07-01'
AND ComStatInYearWeekEnd < '2013-09-30'
AND ComStatInYearCltCode = 'STI02') TotalDiff
UNION
SELECT
(SELECT SUM(ComStatinYearPen)
FROM tblComStatInYear
WHERE ComStatinYearYear = '2014'
AND ComStatInYearWeekEnd > '2014-07-01'
AND ComStatInYearWeekEnd < '2014-09-30'
AND ComStatInYearCltCode = 'STI02')
- (SELECT SUM(ComStatinYearPen)
FROM tblComStatInYear
WHERE ComStatinYearYear = '2013'
AND ComStatInYearWeekEnd > '2013-07-01'
AND ComStatInYearWeekEnd < '2013-09-30'
AND ComStatInYearCltCode = 'STI02') PenDiff
UNION
SELECT
(SELECT SUM(ComStatinYearPrin)
FROM tblComStatInYear
WHERE ComStatinYearYear = '2014'
AND ComStatInYearWeekEnd > '2014-07-01'
AND ComStatInYearWeekEnd < '2014-09-30'
AND ComStatInYearCltCode = 'STI02')
- (SELECT SUM(ComStatInYearPrin)
FROM tblComStatInYear
WHERE ComStatinYearYear = '2013'
AND ComStatInYearWeekEnd > '2013-07-01'
AND ComStatInYearWeekEnd < '2013-09-30'
AND ComStatInYearCltCode = 'STI02') PrinDiff
答案 0 :(得分:0)
解决问题的最简单方法是使用子查询:
select
(select sum(x) from table1) as result1,
(select sum(y) from table2) as result2,
(select sum(z) from table3) as result3
答案 1 :(得分:0)
我对您的数据了解不多,但您可以执行以下操作:
DECLARE @year2014(ComStatinYearTotal_SUM INT, ComStatinYearPen_SUM INT, ComStatinYearPrin_SUM INT)
DECLARE @year2013(ComStatinYearTotal_SUM INT, ComStatinYearPen_SUM INT, ComStatinYearPrin_SUM INT)
INSERT INTO @year2014
SELECT SUM(ComStatinYearTotal), SUM(ComStatinYearPen), SUM(ComStatinYearPrin)
FROM tblComStatInYear
WHERE ComStatinYearYear = '2014'
AND ComStatInYearWeekEnd > '2014-07-01'
AND ComStatInYearWeekEnd < '2014-09-30'
AND ComStatInYearCltCode = 'STI02';
INSERT INTO @year2013
SELECT SUM(ComStatinYearTotal), SUM(ComStatinYearPen), SUM(ComStatinYearPrin)
FROM tblComStatInYear
WHERE ComStatinYearYear = '2013'
AND ComStatInYearWeekEnd > '2013-07-01'
AND ComStatInYearWeekEnd < '2013-09-30'
AND ComStatInYearCltCode = 'STI02';
SELECT t1.ComStatinYearTotal_SUM-t2.ComStatinYearTotal_SUM INT, t1.ComStatinYearPen_SUM - t2.ComStatinYearPen_SUM INT, t1.ComStatinYearPrin_SUM - t2.ComStatinYearPrin_SUM
FROM @year2014 t1, @year2013 t2;
插图:
-- Declare TABLE variables
DECLARE @T1 TABLE (C1 INT, C2 INT, C3 INT);
DECLARE @T2 TABLE (C1 INT, C2 INT, C3 INT);
--Load values
INSERT INTO @T1 VALUES (100, 200, 300);
INSERT INTO @T2 VALUES (10, 20, 30);
-- Apply the Subtract
SELECT T1.C1-T2.C1, T1.C2-T2.C2, T1.C3-T2.C3
FROM @T1 T1, @T2 T2