我正在尝试在查询中使用@ variable1 + @ variable2,但实际上得到的结果为0。
MariaDB 服务器版本: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;
答案 0 :(得分:2)
使用子查询,根本不使用变量:
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
中未聚合的列匹配。答案 1 :(得分:1)
您不能只将@ receivable,@ invoiced和@receivable + @invoiced放在同一选择语句中。 (它们不会按顺序存储值。它们将同时执行。)
首先,您需要将值存储在@ receivable,@ invoiced中,然后使用子查询来计算总数:
set @start_at = '2019-01-01';
set @end_at = '2019-01-16';
set @receivable = 0;
set @invoiced = 0;
SELECT *, A.[Account Receivable] + A.[Invoiced] AS TOTAL FROM (
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'
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) A;