子查询返回多行MySQL错误

时间:2018-03-02 21:42:06

标签: mysql

我想获得三列数据。日期,去年修订版,今年修订版。

这是我所拥有的,但我收到一个错误:“子查询返回超过1行”

然而,目标是拥有超过1行。

SELECT 
    DATE_FORMAT(`date`, "%Y%m%d") AS `Date`,
    (SELECT `amount` AS `Revenue($)` 
        FROM `payments`
        WHERE YEAR(date) = (YEAR(CURRENT_DATE())-1)) AS `Revenue PY($)`, 
    (SELECT `amount` AS `Revenue($)`
        FROM `payments` 
        WHERE YEAR(date) = (YEAR(CURRENT_DATE()))) AS `Revenue CY($)`
FROM `payments`
GROUP BY `Date`

示例数据:

date       | amount
2017-05-17 | 100
2017-05-17 | 200
2017-01-12 | 300
2018-05-17 | 330

预期结果:

Date       | Revenue PY($) | Revenue CY($)
2017-05-17 | 300           | 0
2017-01-12 | 300           | 0
2018-05-17 | 0             | 330

1 个答案:

答案 0 :(得分:0)

尝试一下:

SELECT 
    DATE_FORMAT(`date`, "%Y%m%d") AS `Date`,
    `amount`,
    (SELECT SUM(`amount`) AS `Revenue($)` 
        FROM `payments`
        WHERE YEAR(date) = (YEAR(CURRENT_DATE())-1)) AS `Revenue PY($)`, 
    (SELECT SUM(`amount`) AS `Revenue($)`
        FROM `payments` 
        WHERE YEAR(date) = (YEAR(CURRENT_DATE()))) AS `Revenue CY($)`
FROM `payments`
GROUP BY `Date`

<强>更新

这应该会在更新的问题中得到结果。它获取当前年度记录列表和上一年度记录的另一个列表,然后根据日期将它们组合在一起。为了组合两年中同一个月/日的行,它会添加一个列sort_date,它会省略年份。

SELECT `date`,
    DATE_FORMAT(`date`,'%m%d') as `sort_date`,
    SUM(`Revenue CY`) as `Revenue CY`,
    SUM(`Revenue PY`) as `Revenue PY`
FROM (
    SELECT
        DATE_FORMAT(`date`,'%Y$m$d') as `date`,
        0 as `Revenue PY`,
        sum(`amount`) as `Revenue CY`,
    FROM `payments`
    WHERE YEAR(`date`) = YEAR(CURRENT_DATE())
    UNION ALL
    SELECT
        DATE_FORMAT(`date`,'%Y$m$d') as `date`,
        sum(`amount`) as `Revenue PY`,
        0 as `Revenue CY`,
    FROM `payments`
    WHERE YEAR(`date`) = YEAR(CURRENT_DATE()))
    )
GROUP BY `sort_date`
ORDER BY `sort_date`