【问题标题】:MYSQL - Understanding this SELECT and UNION ALL queryMYSQL - 了解这个 SELECT 和 UNION ALL 查询
【发布时间】:2013-12-05 22:08:54
【问题描述】:

我有这段代码,来自Tom Mac,但我想进行一些更改,但我不明白它是如何工作的。

我正在尝试通过添加UNION ALL SELECT date1, date2 FROM person 来同时添加两个日期列,并尝试将其插入现有的选择函数之间。

我将如何将同一张表中的这两列添加到我的结果中?

这是我正在尝试调整的提供的代码:

select person as Names,
sum(splitScore) as Split_Count,
sum(activeScore) as Active_Count
from
(
select Name1 as person, 
case when Name2 is null then 1 else 0.5 end as splitScore,
case when Active='True' and Name2 is null then 1 when Active='True' and Name2 is not null then 0.5 else 0 end as activeScore 
from person where Name1 is not null
union all
select Name2 as person, 
case when Name1 is null then 1 else 0.5 end as splitScore,
case when Active='True' and Name1 is null then 1 when Active='True' and Name1 is not null then 0.5 else 0 end as activeScore 
from person where Name2 is not null
) t inner join roster s on s.name = t.log
group by person
;

【问题讨论】:

  • 联合中的两个“选择”必须有匹配的列。因此,将这些字段添加到两者以及外部选择中。另外,将它们添加到组中
  • 当你想尝试自己做这样的事情时......只需拆开查询。首先使用最嵌套的部分并添加您需要的信息。尝试了解连接和聚合,确保每次将部件添加回或一起添加时都得到正确的结果。

标签: mysql sql select union alias


【解决方案1】:

要连接的两个查询必须包含相同顺序的相同字段。因此,请参阅下面的示例以及其他字段:

select person as Names,
sum(splitScore) as Split_Count,
sum(activeScore) as Active_Count,
newfield1, newfield2
from
(
select Name1 as person, 
case when Name2 is null then 1 else 0.5 end as splitScore,
case when Active='True' and Name2 is null then 1 when Active='True' and Name2 is not  null then 0.5 else 0 end as activeScore, 
newfield1, newfield2 
from person where Name1 is not null
union all
select Name2 as person, 
case when Name1 is null then 1 else 0.5 end as splitScore,
case when Active='True' and Name1 is null then 1 when Active='True' and Name1 is not null then 0.5 else 0 end as activeScore, 
newfield1, newfield2 
from person where Name2 is not null
) t inner join roster s on s.name = t.log
group by person
;

标准的 UNION 可能如下所示:

SELECT field1, field2 FROM table1
UNION
SELECT field1, field2 from table2

您的查询显然具有额外的复杂性

【讨论】:

  • 感谢您的帮助。我终于明白了!
猜你喜欢
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
相关资源
最近更新 更多