看下这段sql为何报错了 SELECT d.`year`,d.`month`,d.`门店属性`,sum(d.`target_days`) as `target_days` FROM (SELECT DISTINCT c.`year`,c.`month`,c.`餐厅名称`,c.`门店编码`,c.`餐厅原始编号`,c.`品牌`,c.`门店属性`,coalesce(c.`target_days`,0) as `target_days` FROM(SELECT year(a.`日期`) as `year`,month(a.`日期`) as `month`,a.*,case when a.`品牌` like'大王早餐%' then b.`operating_days` else null end as `target_days` from input1 a left JOIN input2 b ON a.`餐厅原始编号`=b.`storeid` AND year(a.`日期`)=b.`Year` AND month(a.`日期`)=b.`Month` WHERE a.`品牌` like'大王早餐%')c WHERE c.`门店属性`='KBF直营店')d GROUP BY 1,2,3 UNION SELECT input1.`Year` as `year`,input1.`Month` as `month`,input1.`属性` as `门店属性`,sum(input1.`operating_days`) as `target_days` from input1 GROUP BY 1,2,3 ORDER BY 3,1,2
时间: 2023-07-13 07:27:28 浏览: 166
1.4_问道1.4服务端_问道服务端all.sql_
5星 · 资源好评率100%
根据给出的 SQL 语句,我发现在使用 `UNION` 操作符连接两个 `SELECT` 语句时,两个查询结果的列数不同。第一个 `SELECT` 语句查询结果包含了 `d.门店属性` 列,而第二个 `SELECT` 语句查询结果包含了 `input1.属性` 列,这两列名字不同,因此在使用 `UNION` 操作符时会报错。
为了解决这个问题,需要确保两个 `SELECT` 语句查询结果的列数和列名完全相同,可以使用别名将列名统一,如将第二个 `SELECT` 语句中的 `input1.属性` 列改为 `门店属性`,这样两个查询结果的列名就完全相同了,可以使用 `UNION` 操作符连接。修改后的 SQL 语句如下:
```
SELECT d.`year`, d.`month`, d.`门店属性`, sum(d.`target_days`) as `target_days`
FROM (
SELECT DISTINCT c.`year`, c.`month`, c.`餐厅名称`, c.`门店编码`, c.`餐厅原始编号`, c.`品牌`, c.`门店属性`, coalesce(c.`target_days`, 0) as `target_days`
FROM (
SELECT year(a.`日期`) as `year`, month(a.`日期`) as `month`, a.*, case when a.`品牌` like '大王早餐%' then b.`operating_days` else null end as `target_days`
FROM input1 a
LEFT JOIN input2 b
ON a.`餐厅原始编号`=b.`storeid` AND year(a.`日期`)=b.`Year` AND month(a.`日期`)=b.`Month`
WHERE a.`品牌` like '大王早餐%'
) c
WHERE c.`门店属性`='KBF直营店'
) d
GROUP BY 1, 2, 3
UNION
SELECT input1.`Year` as `year`, input1.`Month` as `month`, input1.`属性` as `门店属性`, sum(input1.`operating_days`) as `target_days`
FROM input1
GROUP BY 1, 2, 3
ORDER BY 3, 1, 2
```
在这个修改后的 SQL 语句中,第二个 `SELECT` 语句查询结果中的 `input1.属性` 列已经改为 `门店属性` 列,并使用了别名 `门店属性`。这样,在使用 `UNION` 操作符连接两个查询结果时,就不会出现列数和列名不匹配的错误。
阅读全文