我正在尝试在SQL Server 2008中创建一个查询...更好地解释了一些表示例:
FinPeriodNr BalJan BalFeb BalMar BalApr
1 100 100 200 400
2 200 300 100 200
**
**
我希望能够首先对列进行总结,看起来像这样:
FinPeriodNr BalJan BalFeb BalMar BalApr
Sum of rows 300 400 300 600
然后能够总结列以得到这样的总余额:
FinPeriodNr TotalSumofBal
1600
是否可以在一个查询下将所有这些全部归结为SQL,如果是这样,我需要使用什么?交叉表?
到目前为止我的代码只能让我进入第二个表
SELECT dbo.Company.CompanyID, dbo.Company.CompanyName, SUM(dbo.SalesSummaryLedgerCOGBP.BalJan) AS SumBalJan,
SUM(dbo.SalesSummaryLedgerCOGBP.BalFeb) AS SumBalFeb, SUM(dbo.SalesSummaryLedgerCOGBP.BalMar) AS SumBalMar,
SUM(dbo.SalesSummaryLedgerCOGBP.BalApr) AS SumBalApr, SUM(dbo.SalesSummaryLedgerCOGBP.BalMay) AS SumBalMay,
SUM(dbo.SalesSummaryLedgerCOGBP.BalJun) AS SumBalJun, SUM(dbo.SalesSummaryLedgerCOGBP.BalJul) AS SumBalJul,
SUM(dbo.SalesSummaryLedgerCOGBP.BalAug) AS SumBalAug, SUM(dbo.SalesSummaryLedgerCOGBP.BalSep) AS SumBalSep,
SUM(dbo.SalesSummaryLedgerCOGBP.BalOct) AS SumBalOct, SUM(dbo.SalesSummaryLedgerCOGBP.BalNov) AS SumBalNov,
SUM(dbo.SalesSummaryLedgerCOGBP.BalDec) AS SumBalDec
FROM dbo.FinancialPeriodCOGBP INNER JOIN
dbo.SalesSummaryLedgerCOGBP ON dbo.FinancialPeriodCOGBP.FinPeriodNr = dbo.SalesSummaryLedgerCOGBP.FinPeriodNr INNER JOIN
dbo.Company ON dbo.SalesSummaryLedgerCOGBP.CompanyID = dbo.Company.CompanyID
GROUP BY dbo.Company.CompanyName, dbo.Company.CompanyID, dbo.Company.Customer, dbo.FinancialPeriodCOGBP.FinStatusOpen
HAVING (dbo.Company.Customer = 1) AND (dbo.FinancialPeriodCOGBP.FinStatusOpen = 1)
如果有解决方案,请告诉我,因为我已经尝试了很多但是无济于事。
答案 0 :(得分:1)
select
sum(FinPeriodNr) as FinPeriodNr
, sum(BalJan) + sum(BalFeb) + sum(BalMar) + sum(BalApr) as TotalSumofBal
FROM
Tble
答案 1 :(得分:0)
我会建议两件事,WITH ROLLUP,并使用表别名。该列没有全年总计的快捷方式,但行总计的快捷方式是GROUP BY子句中的WITH ROLLUP。此外,根据您发布的查询,您不必通过HAVING子句中的两列选择或排序,因此我将它们从GROUP BY中删除并将它们放在WHERE子句中。这就是我想出来的。
SELECT
Company.CompanyID, Company.CompanyName,
SUM(SaleSL.BalJan) AS SumBalJan, SUM(SaleSL.BalFeb) AS SumBalFeb,
SUM(SaleSL.BalMar) AS SumBalMar, SUM(SaleSL.BalApr) AS SumBalApr,
SUM(SaleSL.BalMay) AS SumBalMay, SUM(SaleSL.BalJun) AS SumBalJun,
SUM(SaleSL.BalJul) AS SumBalJul, SUM(SaleSL.BalAug) AS SumBalAug,
SUM(SaleSL.BalSep) AS SumBalSep, SUM(SaleSL.BalOct) AS SumBalOct,
SUM(SaleSL.BalNov) AS SumBalNov, SUM(SaleSL.BalDec) AS SumBalDec,
SUM(
SaleSL.BalJan + SaleSL.BalFeb + SaleSL.BalMar + SaleSL.BalApr
SaleSL.BalMay + SaleSL.BalJun + SaleSL.BalJul + SaleSL.BalAug
SaleSL.BalSep + SaleSL.BalOct + SaleSL.BalNov + SaleSL.BalDec
) AS SumBalTotal
FROM
dbo.FinancialPeriodCOGBP FP
INNER JOIN dbo.SalesSummaryLedgerCOGBP SaleSL ON FP.FinPeriodNr = SaleSL.FinPeriodNr
INNER JOIN dbo.Company ON SaleSL.CompanyID = Company.CompanyID
WHERE (Company.Customer = 1) AND (FP.FinStatusOpen = 1)
GROUP BY Company.CompanyName, Company.CompanyID WITH ROLLUP