MySQL UNION does not seem to work correctly -
i have sql query using pull data orders database. querying 2 tables , combining results using union all. however, union not seem work expected. here query using:
select year(oc_order.date_added) year, count(oc_order.order_id) cnt, sum( ifnull(oc_order.new_total,oc_order.total) ) total oc_order oc_order.order_status_id in (1,3,5) , month(oc_order.date_added) between '01' , '02' , day(oc_order.date_added) between '01' , '31' group year(oc_order.date_added) union select ifnull(year(str_to_date(oc_return_custom.date_added,'%d-%m-%y %h:%i:%s')),year(str_to_date(oc_return_custom.date_added,'%y-%m-%d %h:%i:%s')) ) year, count(oc_return_custom.return_id) cnt, sum( oc_return_custom.total ) total oc_return_custom ifnull(month(str_to_date(oc_return_custom.date_added,'%d-%m-%y %h:%i:%s')),month(str_to_date(oc_return_custom.date_added,'%y-%m-%d %h:%i:%s')) ) between '01' , '02' , ifnull(day(str_to_date(oc_return_custom.date_added,'%d-%m-%y %h:%i:%s')),day(str_to_date(oc_return_custom.date_added,'%y-%m-%d %h:%i:%s')) ) between '01' , '31' group ifnull(year(str_to_date(oc_return_custom.date_added,'%d-%m-%y %h:%i:%s')),year(str_to_date(oc_return_custom.date_added,'%y-%m-%d %h:%i:%s')) ) order year desc
this query:
+=======+========+=======+ | year | cnt | total | +=======+========+=======+ | 2016 | 200 | 1000 | | 2016 | 50 | 200 | | 2015 | 100 | 800 | | 2015 | 10 | 50 | +=======+========+=======+
but wanted get:
+=======+========+=======+ | year | cnt | total | +=======+========+=======+ | 2016 | 250 | 1200 | | 2015 | 110 | 850 | +=======+========+=======+
can tell me doing wrong???
notes: oc_order table's date_added column datetime whereas oc_return_custom 's date_added column text.
union all
puts 2 data sets produced separate group by
operations.
to expected result set have wrap query in subquery , apply additional group by
:
select year, sum(cnt) cnt, sum(total) total ( ... query here ...) t group year
Comments
Post a Comment