简体   繁体   English

SQL:在TEMP表中使用UNION

[英]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 我正在尝试将去年的销售额与今年的销售额进行比较,而我使用的方法是使用一个临时表,该表包含2个由工会加入的Select语句

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 我收到错误消息:字段名称中的未知列“ thismay”

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. 我的理解方式是我要加入表并将其存储在TEMP表中。

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" . 在您的Temp查询中,您使用UNION ALL ,第一个查询将确定该查询结果中的列名称,因此temp仅生成列theatreNolastMay ,然后在第二个查询中, thisMay将被第一个查询的lastMay ,因此当您在外部查询中选择列thisMay ,它导致未知列“ thismay”

Here is the official doc about UNION : 这是有关UNION的官方文档:

The column names from the first SELECT statement are used as the column names for the results returned. 第一个SELECT语句中的列名用作返回结果的列名。 Selected columns listed in corresponding positions of each SELECT statement should have the same data type. 每个SELECT语句的相应位置中列出的所选列应具有相同的数据类型。 (For example, the first column selected by the first statement should have the same type as the first column selected by the other statements.) (例如,第一条语句选择的第一列应与其他语句选择的第一列具有相同的类型。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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