我试图在查询中使用 @variable1 + @variable2 但实际上给出的结果是 0。
玛丽亚数据库 服务器版本:10.2.21
set @start_at = '2019-01-01';
set @end_at = '2019-01-16';
set @receivable = 0;
set @invoiced = 0;
SELECT DISTINCT Customer.custnr 'Customer Number',
Address.name 'Name',
@receivable := sum(case
WHEN [condition1 <= @start_at]
AND Transactions.`key` not in [subquery]
THEN Transactions.amount
ELSE 0 END) 'Account Receivable',
@invoiced := sum(case
WHEN [condition1 between @start_at and @end_at]
AND [condition2]
AND [condition3]
AND Transactions.`key` not in [subquery]
THEN Transactions.amount
ELSE 0 END) 'Invoiced',
@receivable + @invoiced 'Total'
FROM LocalCust
INNER JOIN Customer
on Customer.`key` = LocalCust.customerkey
INNER JOIN Address
on Address.`key` = Customer.addresskey
INNER JOIN Location
on Location.`key` = LocalCust.localkey
INNER JOIN Transactions
on Transactions.localcustkey = LocalCust.`Key`
GROUP BY Transactions.localcustkey;
最佳答案
使用子查询,完全不使用变量:
SELECT x.*, (Account_Receivable + Invoice) as Total
FROM (SELECT c.custnr as Customer_Number, a.name,
sum(case when condition1 <= @start_at and
t.`key` not in [subquery]
then t.amount
else 0
end) as Account_Receivable,
sum(case when condition1 between @start_at and @end_at and
[condition2] and
[condition3] and
t.`key` not in [subquery]
then t.amount
else 0
end) as Invoiced
FROM LocalCust lc JOIN
Customer c
on c.`key` = lc.customerkey JOIN
Address a
on a.`key` = c.addresskey JOIN
Location l
on l.`key` = lc.localkey join
Transactions t
on t.localcustkey = lc.`Key`
GROUP BY c.custnr, a.name
) x;
注意事项:
- 表别名使查询更易于编写和阅读。
SELECT DISTINCT
几乎不需要GROUP BY
。GROUP BY
键应与SELECT
中的未聚合列相匹配。- 选择不需要转义的列别名。也就是说,没有空格。
关于mysql - 局部变量和前面的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55816886/