基本上我有2张桌子
-dbo.TicketSales -dbo。费用
在我的dbo.Expenses表中,有一个实际有效的查询:
WITH Aggregates AS
(
SELECT
CONVERT(date, Expenses_Date) AS [Date]
,Expenses.Expenses_Desc AS [Description]
,Expenses.Expenses_Remarks AS [Remarks]
,SUM(Expenses.Expenses_Amount) AS [Total Expenses]
FROM dbo.Expenses
GROUP BY CONVERT(date, Expenses_Date),Expenses.Expenses_Desc,Expenses.Expenses_Remarks
)
SELECT
E.[Date],
E.[Description],
E.[Remarks],
E.[Total Expenses]
FROM
Aggregates AS E
UNION ALL
SELECT
[Date] = NULL,
[Description] = NULL,
[Remarks] = 'CURRENT TOTAL EXPENSES',
[Total Expenses] = SUM(E.[Total Expenses])
FROM
Aggregates AS E
我的问题是,如何获取dbo.TicketSales.TotalMoney和Union的总和 它对我现有的结果有影响吗?
答案 0 :(得分:0)
根据您的评论,我认为这是您想要的:
WITH Aggregates AS
(
SELECT
CONVERT(date, Expenses_Date) AS [Date]
,Expenses.Expenses_Desc AS [Description]
,Expenses.Expenses_Remarks AS [Remarks]
,SUM(Expenses.Expenses_Amount) AS [Total Expenses]
FROM dbo.Expenses
GROUP BY CONVERT(date, Expenses_Date),Expenses.Expenses_Desc,Expenses.Expenses_Remarks
)
SELECT
E.[Date],
E.[Description],
E.[Remarks],
E.[Total Expenses]
FROM
Aggregates AS E
UNION ALL
SELECT
[Date] = NULL,
[Description] = NULL,
[Remarks] = 'CURRENT TOTAL EXPENSES',
[Total Expenses] = SUM(E.[Total Expenses])
FROM
Aggregates AS E
UNION ALL
Select
[Date] = NULL,
[Description] = NULL,
[Remarks] = 'CURRENT MONEY',
[Total Expenses] = SUM(TotalMoney)
FROM
TicketSales
UNION ALL
Select
[Date] = NULL,
[Description] = NULL,
[Remarks] = 'DIFFERENCE',
[Total Expenses] = (
(Select SUM(TotalMoney) from TicketSales)
-(Select SUM(E.[Total Expenses]) from Aggregates AS E)
)