在 SELECT 中重用别名

发布于 2024-11-29 21:25:14 字数 241 浏览 0 评论 0原文

我想做的是添加另一列来计算 (cr - dr)

鉴于您无法在 SELECT 子句中重复使用别名,您将如何计算 total

    SELECT SUM(b.bet_win * cy.fx_rate )as dr, SUM(b.bet_loss * cy.fx_rate ) as cr, cr+dr as total
    FROM ....
    WHERE ....

What I am trying to do is add another column that calculates (cr - dr)

Seeing as you cannot re-use an alias inside a SELECT clause, how would you go about calculatin total

    SELECT SUM(b.bet_win * cy.fx_rate )as dr, SUM(b.bet_loss * cy.fx_rate ) as cr, cr+dr as total
    FROM ....
    WHERE ....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

平定天下 2024-12-06 21:25:14

在 SQL Server 或 Oracle 中,我会使用 CTE,但由于您使用的是 MySQL,因此您会使用子查询:

SELECT dr, cr, cr + dr as total 
FROM (
    SELECT 
         SUM(b.bet_win * cy.fx_rate ) as dr, 
         SUM(b.bet_loss * cy.fx_rate ) as cr
    FROM ....
    WHERE ....) t;

In SQL Server or Oracle, I'd use a CTE, but since you're using MySQL, you'd use a subquery:

SELECT dr, cr, cr + dr as total 
FROM (
    SELECT 
         SUM(b.bet_win * cy.fx_rate ) as dr, 
         SUM(b.bet_loss * cy.fx_rate ) as cr
    FROM ....
    WHERE ....) t;
雪落纷纷 2024-12-06 21:25:14

编辑:不起作用。见评论。
在这种情况下,使用用户变量更快?

SELECT
  @dr:=SUM(b.bet_win * cy.fx_rate ),
  @cr:=SUM(b.bet_loss * cy.fx_rate ), 
  @cr+@dr as total

EDIT: DOES NOT WORK. See comments.
Isn't using a user variable faster in this case?

SELECT
  @dr:=SUM(b.bet_win * cy.fx_rate ),
  @cr:=SUM(b.bet_loss * cy.fx_rate ), 
  @cr+@dr as total
半城柳色半声笛 2024-12-06 21:25:14

您可以在“总计”栏中重复计算。

SELECT 
    SUM(b.bet_win * cy.fx_rate) as dr, 
    SUM(b.bet_loss * cy.fx_rate) as cr, 
    SUM(b.bet_win * cy.fx_rate) + SUM(b.bet_loss * cy.fx_rate) as total
FROM ....
WHERE ....

You can repeat the calculations in the "total" column.

SELECT 
    SUM(b.bet_win * cy.fx_rate) as dr, 
    SUM(b.bet_loss * cy.fx_rate) as cr, 
    SUM(b.bet_win * cy.fx_rate) + SUM(b.bet_loss * cy.fx_rate) as total
FROM ....
WHERE ....
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文