我首先发布我的查询...
SELECT [copyright status],
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
GROUP BY [copyright status]
UNION
SELECT [lw status],
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
WHERE [lw status] = 'In Reserve'
GROUP BY [lw status]
UNION
SELECT [lw status],
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
WHERE [lw status] = 'Published'
GROUP BY [lw status];
(希望这很容易阅读)
它按照我的意图工作,但是我想在查询中再添加一个函数。
在第一次SELECT
查询之后,我想添加一个额外的查询,该查询总计三个总和中的每一个(关键信息,方法,研究)。我尝试添加的语法如下:
<Previous Query>
UNION
SELECT,
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
UNION
<Next Query>
但是,当我尝试运行它时,我收到一条错误,其中显示“联合查询的两个选定查询表中的列数不匹配。”
我不确定我是否过于雄心勃勃。
此外,是否有更有效的格式化初始查询的方法?
如果它有所不同,图层,版权状态和lw状态中的值将存储在单独的表中,并通过表设计模式中的组合框绘制到资源表中。我正在使用Access 2003。
如果需要更多信息,请告知我们。
感谢。
答案 0 :(得分:2)
union
的所有部分的列数必须相等。您只需为摘要行添加null
第一列:
SELECT null,
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
答案 1 :(得分:1)
您已移除lw status
但未选择任何内容:
UNION
SELECT 'SUM',
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
UNION
<Next Query>
答案 2 :(得分:1)
UNION中的每个SELECT应具有相同数量的字段(在您的情况下为4)。 也许只需在SELECT中添加“stub”字段,例如空值?
UNION
SELECT
NULL, -- <- STUB (for padding only)
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
UNION