2

我将从发布我的查询开始...

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>

但是,当我尝试运行它时,我收到一条错误消息,显示“联合查询的两个选定查询表中的列数不匹配”。

我不确定我是否对此过于雄心勃勃。

此外,是否有更有效的方式来格式化初始查询?

如果有什么不同,layer、copyright status 和 lw status 中的值分别存储在单独的表中,并通过表格设计模式中的组合框绘制到资源表中。我正在使用 Access 2003。

如果需要更多信息,请告诉我。

谢谢。

4

3 回答 3

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
于 2013-06-20T10:42:54.473 回答
1

UNION 中的每个 SELECT 都应该具有相同数量的字段(在您的情况下为 4 个)。也许只是将“存根”字段添加到 SELECT 中,例如 NULL?

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 
于 2013-06-20T10:46:46.323 回答
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>
于 2013-06-20T10:40:51.373 回答