如何在选择查询中使用案例别名

Posted

技术标签:

【中文标题】如何在选择查询中使用案例别名【英文标题】:How can i use case alias in a select query 【发布时间】:2021-04-30 01:59:52 【问题描述】:

在 SQL 中,我,有问题的是一个计数,例如,您将在下面看到选择别名设置为 as,但我不能在其余部分中使用别名选择查询。使用 mysql

下面有问题的行是: (win / total) * 100 as win_percent

    DECLARE @team TEXT;
    SET @team = "myTeam";
    SELECT 
        @team team,
        COUNT(CASE WHEN home = @team then 1 ELSE NULL END) as home,
        COUNT(CASE WHEN away = @team then 1 ELSE NULL END) as away,
        COUNT(CASE WHEN (away = @team or home = @team) then 1 ELSE NULL END) as total,
        COUNT(CASE WHEN winner = @team and (home = @team or away = @team)  then 1 ELSE NULL END) as win,    
        COUNT(CASE WHEN (home = @team or away = @team) and (winner <> @team and winner <> "0") then 1 ELSE NULL END) as lost,
        COUNT(CASE WHEN winner = "0" and (home = @team or away = @team) then 1 ELSE NULL END) as tie,
        (869 / 1928) * 100 as win_percent,
        (win / total) * 100 as win_percent
    from matches;

【问题讨论】:

不行。使用表达式而不是别名。或者将您的查询移动到子查询/CTE 中,并在外部查询中使用 win/total 列值。 【参考方案1】:

您可以创建一个子查询并将最终的 win_percent 放在最外层的查询中。查询应如下所示:

SELECT a.*,
    (win / total) * 100 as win_percent
FROM (
SELECT 
        @team team,
        COUNT(CASE WHEN home = @team then 1 ELSE NULL END) as home,
        COUNT(CASE WHEN away = @team then 1 ELSE NULL END) as away,
        COUNT(CASE WHEN (away = @team or home = @team) then 1 ELSE NULL END) as total,
        COUNT(CASE WHEN winner = @team and (home = @team or away = @team)  then 1 ELSE NULL END) as win,    
        COUNT(CASE WHEN (home = @team or away = @team) and (winner <> @team and winner <> "0") then 1 ELSE NULL END) as lost,
        COUNT(CASE WHEN winner = "0" and (home = @team or away = @team) then 1 ELSE NULL END) as tie,
        (869 / 1928) * 100 as win_percent
    from matches
) AS a

【讨论】:

按预期工作谢谢,将在 3 分钟内设置为答案。【参考方案2】:

我建议简化您的查询,使用方便的 MySQL 扩展,将布尔值视为数字,1 为真,0 为假:

SELECT @team team,
       SUM(home = @team) as home,
       SUM(away = @team) as away,
       SUM(@team IN (away, home))) as total,
       SUM(winner = @team and @team IN (away, home)) as win,    
       SUM(winner <> @team and winner <> 0 and @team IN (away, home)) as lost,    
       SUM(winner = '0' and @team IN (away, home)) as tie,
       (869 / 1928) * 100 as win_percent,
       AVG(CASE WHEN @team IN (away, home) THEN winner = @team END) as win_percent

【讨论】:

以上是关于如何在选择查询中使用案例别名的主要内容,如果未能解决你的问题,请参考以下文章

如何在 mySQL 中使用案例编写生肖查询

如何在sequelize中选择案例查询?

如何在 Informix 数据库表中使用列别名

在同一选择中使用列别名[重复]

如何在查询中使用别名字段? (甲骨文10g)

如何从子查询中获取 ResultSet 的别名?