SELECT c.Category, SUM(c.[Market Value]), SUM([p.Market Value])
FROM Dec AS c, [NOV] as p
GROUP BY c.Category
;
告诉我该类别不是聚合函数的一部分。我只是想看看两个表的每个类别的总和。我不想只显示某些值,所以我应该使用Join?
编辑:
SELECT c.[Category], SUM(c.[Market Value]), SUM(p.[Market Value])
FROM Dec AS c
INNER JOIN Nov AS p ON c.ID = p.ID
GROUP BY c.category, p.Category
;
这是我用JOIN编写的,它只是运行不间断的查询。我等一下吗?有80,000行数据,但只按一个月按类别进行一次SUM会立即返回,为什么两张表很难?
答案 0 :(得分:1)
您需要UNION所有数据:
SELECT Category, [market Value]
FROM DEC
UNION ALL
SELECT Category, [market Value]
FROM NOV
运行此查询时,您将获得两个月的合并数据。如果您想获得组合数据的总和,只需使用查询:
SELECT Category, SUM([market Value]) as sum_value
FROM (
SELECT Category, [market Value]
FROM DEC
UNION ALL
SELECT Category, [market Value]
FROM NOV
) as A
GROUP BY Category
现在,这不是你想要的。你想要两列:一列是十一月,一列是十二月。要做到这一点,你需要稍微修改UNION ALL查询:
SELECT Category, [market Value], 'Dec' as type
FROM DEC
UNION ALL
SELECT Category, [market Value], 'Nov' as type
FROM NOV
最终的查询将是:
SELECT Category,
SUM(iif(type='Dec', [Market Value], 0)) as Dec_Value,
SUM(iif(type='Nov', [Market Value], 0)) as Nov_Value
FROM (
SELECT Category, [market Value], 'Dec' as type
FROM DEC
UNION ALL
SELECT Category, [market Value], 'Nov' as type
FROM NOV
) as A
GROUP BY Category