Question

I'll start by posting my query...

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];

(Hope that is easy to read)

Its working as I intend it to, however I would like to add one more function to the query.

After the first SELECT query, I would like to add in an additional query which totals each each of the three sums (Key Info, Approaches, Research). The syntax I tried adding in was as follows:

<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>

However, when I try and run it, I get an error which reads "The number of columns in the two selected tables of queries of a union query do not match."

I'm not sure if I'm being too ambitious with this.

Also, is there a more efficient way of formatting the initial query?

If it makes any difference, the values in layer, copyright status and lw status are stored in seperate tables and drawn into the resources table via a combo box in the table design mode. I'm using Access 2003.

If any more info is required, please let me know.

Thanks.

Was it helpful?

Solution

The number of columns has to be equal for all parts of the union. You could just add a null first column for your summary row:

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

OTHER TIPS

You removed lw status and didn't select anything:

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>

Each SELECT within UNION should have the same number of fields (4 in your case). Mayhaps just add "stub" field into SELECT, e.g. 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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top