[英]Subquery returns more than 1 row MySQL Error
I am trying to get three columns of data. 我正在尝试获取三列数据。 Date, Last Years Rev, This Years Rev. 日期,去年版本,今年版本。
Here is what I have, but I get an error: "Subquery returns more than 1 row" 这是我所拥有的,但是出现错误:“子查询返回的行数超过1”
However the goal is to have more than 1 row. 但是,目标是要多于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`
Sample Data: 样本数据:
date | amount
2017-05-17 | 100
2017-05-17 | 200
2017-01-12 | 300
2018-05-17 | 330
Expected Outcome: 预期结果:
Date | Revenue PY($) | Revenue CY($)
2017-05-17 | 300 | 0
2017-01-12 | 300 | 0
2018-05-17 | 0 | 330
Give this a try: 试试看:
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`
UPDATE 更新
This should get the results as in your updated question. 如您更新的问题,这应该获得结果。 It gets a list of current year records and another list of previous year records, then combines them based on date. 它获取当前年份记录的列表和先前年份记录的另一个列表,然后根据日期将它们合并。 In order to combine rows from the same month/day from the two years, it adds a column sort_date which omits the year. 为了合并两年中同一月/日的行,它添加了一列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`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.