gpt4 book ai didi

mysql - 在选择查询中包括未找到直接结果的占位符结果

转载 作者:行者123 更新时间:2023-11-29 06:34:18 25 4
gpt4 key购买 nike

我有一张比赛结果表。并非所有参赛者都会参加每场比赛,但我想在一个表格中显示他们未参加的比赛,并在结果列中使用空格和连字符“-”值。

例如,参赛者“John Smith”没有参加 2004 年或 2005 年的比赛,但我希望打印这些赛事,即使他的名字没有出现在数据库中这些比赛的记录中.

我只希望在系列赛(“srs”)以及他在那一年的系列赛中至少参加一场比赛的年份中发生这种情况。因此,他在 2003 年没有参加任何比赛,因此甚至没有连字符结果显示。

到目前为止,我已经生成了这段代码,但它没有按预期工作 - 它包括竞争对手的结果和他参加的比赛的连字符。

以下内容应有助于解释我寻求实现的结果结构类型:

a busy cat

我尝试过使用 UNION 显示的查询。我想我(希望)错过了一个小技巧。

select series as srs, 
year as yr,
concat(year,series) as yrsrs,
concat(year,series,round) as yrsrsrd,
round,
venue,
result
from races
where competitor = "John Smith"
group by yrsrsrd limit 200
UNION
select series as srs,
year as yr,
concat(year,series) as yrsrs,
concat(year,series,round) as yrsrsrd,
round,
venue,
case when competitor <> "John Smith" then "-" else result end
from races
group by yrsrsrd order by 2, 1, 5 limit 200

最佳答案

您只需要查询的第二部分,但需要更改结果的计算。

select series as srs, 
year as yr,
concat(year,series) as yrsrs,
concat(year,series,round) as yrsrsrd,
round,
venue,
coalesce(sum(case when competitor = "John Smith" then result end), "-") as result
from races
group by yrsrsrd
order by 2, 1, 5
limit 200

现在从内到外看这条线:

coalesce(sum(case when competitor = "John Smith" then result end), "-") as result

CASE 表达式将仅返回 John Smith 的结果。对于同一组(竞赛)中的所有其他行,它将为 NULL。 SUM 函数将忽略所有 NULL,只保留 J.S. 的结果。如果 J.S.没有参加过那场比赛,SUM 的所有元素都将为 NULL,因此 SUM 将返回 NULL。最后 COALESCE 会将 NULL 转换为“-”。

关于mysql - 在选择查询中包括未找到直接结果的占位符结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54632175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com