SQL-如何对其他3个查询的列求和

时间:2018-11-30 20:02:17

标签: sql ms-access sum

我希望从查询生成的3个表中总计3列。这三个表是Payroll_Table,Misc_Table,Depreciation_Table。每个表都有Store_ID和Payroll_Expense或Misc_Expense或Depreciation_Expense列。

我正在尝试获取每个Store_ID的工资,杂项和折旧的总额。

SELECT Store_ID, SUM(Payroll_Expense + Misc_Expense + Depreciation_Expense) AS Total
FROM (
SELECT Store_ID, Payroll_Expense FROM [Payroll_Table]UNION ALL
SELECT Store_ID, Misc_Expense AS FROM [Misc_Table] UNION ALL
SELECT Store_ID, Depreciation_Expense FROM [Depreciation_Table]
)
GROUP BY Store_ID

如果运行此查询,则会提示您输入Misc_Expense和Depreciation_Expense的“输入参数值”。如果输入1,我将获得正确的值,但不确定为什么会收到此提示。

2 个答案:

答案 0 :(得分:2)

UNION时,您不能引用不同的列名称,而应引用该列的索引/位置或为这些列加上别名:

SELECT Store_ID, SUM(Expense) AS Total
FROM (
SELECT Store_ID, Payroll_Expense AS [Expense] FROM [Payroll_Table]UNION ALL
SELECT Store_ID, Misc_Expense AS [Expense] FROM [Misc_Table] UNION ALL
SELECT Store_ID, Depreciation_Expense AS [Expense] FROM [Depreciation_Table]
)
GROUP BY Store_ID

答案 1 :(得分:0)

因此,工会仅生成两列store_ID和“ Expense”(实际上是Payroll_Expense)

系统不知道misc_expense和depreciation_expense是什么;这就是为什么提示您同时选择两者的原因。如果您从派生表中进行选择*,如下所示:

SELECT * 
FROM (
SELECT Store_ID, Payroll_Expense Expense FROM [Payroll_Table]UNION ALL
SELECT Store_ID, Misc_Expense FROM [Misc_Table] UNION ALL
SELECT Store_ID, Depreciation_Expense FROM [Depreciation_Table]
) DerivedTable

因此,基于此您可以看到没有MISC_EXPENSE列和Depreciation_Expense;它们全部都计入Payroll_Expense(费用)。因此,派生表只有2列,而不是外部选择所期望的4列。我们仍然可以得到4;您只需要使用下面的选项2;但是需要吗?

要解决: 只需在外部查询中省略Misc_Expense和Depreciation_Expense,就可以将它们作为“ Expense”列中的值,并为后代添加别名。

联合中每个列的列名和数据类型都继承自第一个查询的列名和数据类型;除非为null,否则它是遇到的第一个数据类型。

所以我们可以这样做:

SELECT Store_ID, SUM(Expense) AS Total
FROM (
SELECT Store_ID, Payroll_Expense AS Expense FROM [Payroll_Table]UNION ALL
SELECT Store_ID, Misc_Expense FROM [Misc_Table] UNION ALL
SELECT Store_ID, Depreciation_Expense FROM [Depreciation_Table]
) as DerivedTable
GROUP BY Store_ID

如果由于某种原因您仍然需要全部3列,则需要为其他两列使用占位符。 (选项2)

SELECT Store_ID, SUM(Payroll_Expense + Misc_Expense + Depreciation_Expense) AS Total
FROM (
SELECT Store_ID
     , Payroll_Expense
     , NULL as Misc_expense
     , Null as Depreciation_expense 
FROM [Payroll_Table] UNION ALL
SELECT Store_ID
     , NULL as Payroll_Expense
     , Misc_Expense
     , Null as Depreciation_expense
FROM [Misc_Table] UNION ALL
SELECT Store_ID
     , Null as Payroll_expense
     , Null as Misc_expense
     , Depreciation_Expense 
FROM [Depreciation_Table]
) as DerivedTable
GROUP BY Store_ID