MySQL子查询返回多行

时间:2017-06-22 19:32:41

标签: mysql subquery

SELECT CONCAT(MONTH(revenue_date),"/ ", YEAR(revenue_date)) as month_year, 

    (SELECT COUNT(DISTINCT DATE(delivery_date)) as operating_days
    FROM table2 where weekday(delivery_date) <> 5 and     
    weekday(delivery_date) <> 6 and delivery_date < current_time and     
    year(delivery_date) > 2015 GROUP BY YEAR(delivery_date), MONTH(delivery_date)), 
sum(revenue) as total_revenue,
from table1 
where revenue_date < current_time and year(revenue_date) > 2015
group by year(revenue_date), month(revenue_date);

这表示错误&#34;子查询返回的值超过1&#34;。如果我不在子查询中包含group by,则它只返回所有月份的总数,但我需要它在所有月份单独返回。

2 个答案:

答案 0 :(得分:0)

加入子查询。

SELECT DATE_FORMAT('%c/%Y', revenue_date) as month_year, 
        sum(revenue) as total_revenue, operating_days
from table1
JOIN (SELECT YEAR(delivery_date) AS delivery_year, MONTH(delivery_date) AS delivery_month, 
            COUNT(DISTINCT DATE(delivery_date)) as operating_days
    FROM table2 
    where weekday(delivery_date) <> 5 and     
        weekday(delivery_date) <> 6 and delivery_date < current_time and     
        year(delivery_date) > 2015 
    GROUP BY delivery_year, delivery_month) AS t2 
ON YEAR(revenue_date) = delivery_year AND MONTH(revenue_date) = delivery_month
where revenue_date < current_time
group by year(revenue_date), month(revenue_date);

答案 1 :(得分:0)

试试这个:

SELECT CONCAT(MONTH(revenue_date),"/ ", YEAR(revenue_date)) as month_year, a.operating_days
sum(revenue) as total_revenue,
from table2 JOIN
(SELECT YEAR(delivery_date) as `year`, MONTH(delivery_date) as `month`, COUNT(DISTINCT DATE(delivery_date)) as operating_days
    FROM table2 where weekday(delivery_date) <> 5 and     
    weekday(delivery_date) <> 6 and delivery_date < current_time and     
    year(delivery_date) > 2015 GROUP BY YEAR(delivery_date), MONTH(delivery_date)) a
ON year(revenue_date) = a.year AND month(revenue_date) = a.month
where revenue_date < current_time and year(revenue_date) > 2015
group by year(revenue_date), month(revenue_date);