简体   繁体   中英

SQL: Using UNION Inside a TEMP Table

Coursework question so please don't give me the answer!

I'm trying to compare last years sales to this years sales and the approach I'm using is using a temp table which contains 2 Select statements joined by a union

SELECT theatreNo,  SUM(lastMay) AS lastMay, SUM(thisMay) AS thisMay
FROM(
    SELECT
    theatreNo,
    COUNT(*) AS lastMay
    FROM Hospital_Operation
    WHERE year(startDateTime) = '2015' and month(startDateTime) = '05' 
    GROUP BY theatreNo, DATE_FORMAT(startDateTime, '%d%c%y')
    UNION ALL
    SELECT
    theatreNo,
    COUNT(*) AS thisMay
    FROM Hospital_Operation
    WHERE year(startDateTime) = '2016' and month(startDateTime) = '05' 
    GROUP BY theatreNo, DATE_FORMAT(startDateTime, '%d%c%y')
)AS Temp
GROUP BY theatreNo;

I'm getting the error: Unknown column "thismay" in field name

Could someone explain to me why I am getting this error? The way my understanding is that I am joining to tables and storing it in the TEMP table.

Firstly, give you a approach here.

SELECT theatreNo,  SUM(lastMay) AS lastMay, SUM(thisMay) AS thisMay
FROM(
    SELECT
    theatreNo,
    COUNT(*) AS lastMay,
    0 AS thisMay
    FROM Hospital_Operation
    WHERE year(startDateTime) = '2015' and month(startDateTime) = '05' 
    GROUP BY theatreNo, DATE_FORMAT(startDateTime, '%d%c%y')
    UNION ALL
    SELECT
    theatreNo,
    0 AS lastMay,
    COUNT(*) AS thisMay
    FROM Hospital_Operation
    WHERE year(startDateTime) = '2016' and month(startDateTime) = '05' 
    GROUP BY theatreNo, DATE_FORMAT(startDateTime, '%d%c%y')
)AS Temp
GROUP BY theatreNo;

then let's do some explanation:

In your Temp query, you used UNION ALL , the first query will decide the column name in this query's result, so temp only produce column theatreNo and lastMay , then in second query, thisMay will be overridden by the first query's lastMay , so when you select column thisMay in external query, it caused Unknown column "thismay" .

Here is the official doc about UNION :

The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type. (For example, the first column selected by the first statement should have the same type as the first column selected by the other statements.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM