让我感到困惑..总左计算似乎不起作用。
我正在尝试获得总凭证并获得总使用量和总剩余数。
请帮忙。
SELECT
(IFNULL(SUM(value), 0)) AS total_voucher,
(
SELECT
IFNULL(SUM(value), 0))
FROM
voucher_history
WHERE
idUser = 1 AND isUsed = 1 AND DATE(FROM_UNIXTIME(datetime)) = '2014-03-04'
) AS total_used,
(total_voucher-total_used) AS total_left
FROM
voucher_history
WHERE
idUser = 1 AND isUsed = 0 AND DATE(FROM_UNIXTIME(datetime)) <= '2014-03-05'
答案 0 :(得分:3)
您可以使用条件聚合执行此操作,而不是使用子查询:
SELECT coalesce(SUM(value), 0)) AS total_voucher,
sum(case when is_used = 1 then value else 0 end) as total_used,
sum(case when is_used = 1 then 0 else value end) as total_left
FROM voucher_history
WHERE idUser = 1 AND DATE(FROM_UNIXTIME(datetime)) <= '2014-03-05';
您的查询存在问题,即它尝试在同一total_voucher
语句中使用列别名(total_used
和select
)。 SQL不支持这一点。您需要使用子查询来获得该功能。