Use join for three tables - mysql

I have three tables and I would like sum over values by month from three tables.
The structure of database:
1)costs_1
-id
-total
-updated_at(timestamp)
2)costs_2
-id
-total_1
-updated_at_1(timestamp)
3)costs_3
-id
-total_2
-updated_at_2(timestamp)
Structure of result table: 1)total; 2)total_1; 3)total_2; 4)month
I have code that work for two tables, but don't know how to adapte it
SELECT t1.y year,
t1.m month,
COALESCE(t1.total, 0),
COALESCE(t2.total, 0)
FROM
(
SELECT YEAR(date_month) y,
MONTH(date_month) m,
SUM(total) total
FROM market_costs
GROUP BY YEAR(date_month), MONTH(date_month)
) t1
LEFT JOIN
(
SELECT YEAR(date_month) y,
MONTH(date_month) m,
SUM(total) total
FROM general_costs
GROUP BY YEAR(date_month), MONTH(date_month)
) t2 ON t1.y = t2.y and t1.m = t2.m
UNION
SELECT t2.y year,
t2.m month,
COALESCE(t1.total, 0),
COALESCE(t2.total, 0)
FROM
(
SELECT YEAR(date_month) y,
MONTH(date_month) m,
SUM(total) total
FROM market_costs
GROUP BY YEAR(date_month), MONTH(date_month)
) t1
RIGHT JOIN
(
SELECT YEAR(date_month) y,
MONTH(date_month) m,
SUM(total) total
FROM general_costs
GROUP BY YEAR(date_month), MONTH(date_month)
) t2 ON t1.y = t2.y and t1.m = t2.m

Combine the 3 tables using UNION ALL then group the data:
SELECT
YEAR(t1.date_month) y
, MONTH(t1.date_month) m
, SUM(t1.total) total
, SUM(t1.total_1) total_1
, SUM(t1.total_2) total_2
FROM (
SELECT
date_month
, total
, NULL as total_1
, NULL as total_2
FROM costs
UNION ALL
SELECT
date_month
, NULL as total
, total_1
, NULL as total_2
FROM costs_1
UNION ALL
SELECT
date_month
, NULL as total
, NULL as total_1
, total_2
FROM costs_2
) t1
GROUP BY
YEAR(t1.date_month)
, MONTH(t1.date_month)
added
SELECT
YEAR(t1.date_month) y
, MONTH(t1.date_month) m
, SUM(t1.total) total
, SUM(t1.total_1) total_1
, SUM(t1.total_2) total_2
FROM (
SELECT
date_month
, total
, NULL as total_1
, NULL as total_2
FROM costs
UNION ALL
SELECT
date_month
, NULL as total
, total as total_1 -- changed
, NULL as total_2
FROM costs_1
UNION ALL
SELECT
date_month
, NULL as total
, NULL as total_1
, total as total_2 -- changed
FROM costs_2
) t1
GROUP BY
YEAR(t1.date_month)
, MONTH(t1.date_month)

Related

sum over values by month from two table

How to sum over values by month from two table?
I have two table:
1)costs_1
-id
-total
-updated_at(timestamp)
2)costs_2
-id
-total_1
-updated_at_1(timestamp)
The result table need have next columns:
-total
-total_1
-month
For example, if I have one table I do next query:
SELECT SUM(total), MONTH(updated_at), YEAR(updated_at) FROM product_sale GROUP BY MONTH(updated_at), YEAR(updated_at) ORDER by MONTH(updated_at)
I believe you want something like this.
SELECT t1.y year,
t1.m month,
t1.total,
t2.total
FROM
(
SELECT YEAR(updated_at) y,
MONTH(updated_at) m,
SUM(total) total
FROM costs_1
GROUP BY YEAR(updated_at), MONTH(updated_at)
) t1
JOIN
(
SELECT YEAR(updated_at_1) y,
MONTH(updated_at_1) m,
SUM(total_1) total
FROM costs_2
GROUP BY YEAR(updated_at_1), MONTH(updated_at_1)
) t2 ON t1.y = t2.y and t1.m = t2.m
However, in this solution, you will miss a month if costs_1 or costs_2 does not have any record with the month. If you want FULL JOIN you have to emulate it in mysql using two OUTER JOINS like this:
SELECT t1.y year,
t1.m month,
COALESCE(t1.total, 0),
COALESCE(t2.total, 0)
FROM
(
SELECT YEAR(updated_at) y,
MONTH(updated_at) m,
SUM(total) total
FROM costs_1
GROUP BY YEAR(updated_at), MONTH(updated_at)
) t1
LEFT JOIN
(
SELECT YEAR(updated_at_1) y,
MONTH(updated_at_1) m,
SUM(total_1) total
FROM costs_2
GROUP BY YEAR(updated_at_1), MONTH(updated_at_1)
) t2 ON t1.y = t2.y and t1.m = t2.m
UNION
SELECT t2.y year,
t2.m month,
COALESCE(t1.total, 0),
COALESCE(t2.total, 0)
FROM
(
SELECT YEAR(updated_at) y,
MONTH(updated_at) m,
SUM(total) total
FROM costs_1
GROUP BY YEAR(updated_at), MONTH(updated_at)
) t1
RIGHT JOIN
(
SELECT YEAR(updated_at_1) y,
MONTH(updated_at_1) m,
SUM(total_1) total
FROM costs_2
GROUP BY YEAR(updated_at_1), MONTH(updated_at_1)
) t2 ON t1.y = t2.y and t1.m = t2.m
Try this:
SELECT total, total_1, MONTHNAME(costs_1.updated_at) from costs_1 INNER JOIN costs_2
ON
MONTH(costs_1.updated_at)=MONTH(costs_2.updated_at)

MySQL Want to SUM and Minus from two SQL statements

I want to SUM the first Statement(A) and Second Statement(B) Then I want to get the result of A-B. After that I get the output GROUP BY who
SELECT `who`, mpoints-spoints AS netpoints
FROM
(
SELECT `who`,`points`, SUM(points) AS mpoints FROM `game` WHERE (`datetime` BETWEEN '2015-12-1' AND '2015-12-31') AND (`cal`='1') AND (`result`='1' OR `result`='2') GROUP BY `who`
) t1,
(
SELECT `who`,`points`, SUM(points) AS spoints FROM `game` WHERE (`datetime` BETWEEN '2015-12-1' AND '2015-12-31') AND (`cal`='1') AND (`result`='3' OR `result`='4') GROUP BY `who`
) t2
ORDER BY netpoints DESC
GROUP BY `who`
I want the output like
whlie($rs=mysql_fetch_assoc($query)){
No. Who. Points
$i++ $rs['who'] $rs['netpoints']
}
The query could look like the following, but I have not tested it.
SELECT `who`, mpoints-spoints AS netpoints
FROM
(
SELECT `who`,`points`, SUM(points) AS mpoints, 0 as spoints FROM `game` WHERE (`datetime` BETWEEN '2015-12-1' AND '2015-12-31') AND (`cal`='1') AND (`result`='1' OR `result`='2') GROUP BY `who`
UNION ALL
SELECT `who`,`points`, 0 as mpoints, SUM(points) AS spoints FROM `game` WHERE (`datetime` BETWEEN '2015-12-1' AND '2015-12-31') AND (`cal`='1') AND (`result`='3' OR `result`='4') GROUP BY `who`
) A
GROUP BY `who`
ORDER BY netpoints;

Select in select - Every derived table must have its own alias error

I'm trying to get from database information about orders grouped by date.
I have table sales_flat_order, where I have it's id, order creation date, total_paid for order, and order item count. And I have table sales_flat_order_item where are orders items with it prices.
I created script to get order information by day:
SELECT
DATE( sales_flat_order.created_at ) AS date,
SUM( sales_flat_order.total_paid ) AS sales,
SUM( sales_flat_order.total_item_count ) AS items
FROM
sales_flat_order,
sales_flat_order_payment
WHERE
sales_flat_order.status = 'complete'
AND sales_flat_order.entity_id = sales_flat_order_payment.parent_id
AND sales_flat_order_payment.method = 'checkmo'
GROUP BY DATE( sales_flat_order.created_at )
WITH ROLLUP
I get:
DATE SALES ITEMS
2013-03-05 72 3
2013-03-06 100 5
And I have script to count median price:
SELECT
avg(t1.price) as median_val
FROM
(
SELECT
#rownum:=#rownum+1 as `row_number`,
d.price
FROM
sales_flat_order_item d,
(SELECT #rownum:=0) r
WHERE 1
ORDER BY d.price
) as t1,
(
SELECT
count(*) as total_rows
FROM
sales_flat_order_item d
WHERE 1
) as t2
WHERE 1
AND t1.row_number>=total_rows/2
and t1.row_number<=total_rows/2+1;
Now I'm trying to combine this two script to get:
DATE SALES ITEMS median_item_price
2013-03-05 72 3 19
2013-03-06 100 5 10.5
Combined script:
SELECT
DATE( sales_flat_order.created_at ) AS date,
SUM( sales_flat_order.total_paid ) AS sales,
SUM( sales_flat_order.total_item_count ) AS items,
sales_flat_order_item.price as median_item_price
FROM
sales_flat_order,
sales_flat_order_payment,
(
SELECT
avg(t1.price) as median_val
FROM
(
SELECT
#rownum:=#rownum+1 as `row_number`,
d.price
FROM
sales_flat_order_item d,
(SELECT #rownum:=0) r
WHERE 1
ORDER BY d.price
) as t1,
(
SELECT
count(*) as total_rows
FROM
sales_flat_order_item d
WHERE 1
) as t2
WHERE 1
AND t1.row_number>=total_rows/2
and t1.row_number<=total_rows/2+1
) as sales_flat_order_item
WHERE
sales_flat_order.status = 'complete'
AND sales_flat_order.entity_id = sales_flat_order_payment.parent_id
AND sales_flat_order_payment.method = 'checkmo'
AND DATE(sales_flat_order_item.created_at) = DATE(sales_flat_order.created_at)
GROUP BY DATE( sales_flat_order.created_at )
WITH ROLLUP
and get error: #1248 - Every derived table must have its own alias
here is database: http://sqlfiddle.com/#!2/7dfec
Can anyone help?
Solution:
SELECT
DATE( sales_flat_order.created_at ) AS date,
SUM( sales_flat_order.total_paid ) AS sales,
SUM( sales_flat_order.total_item_count ) AS items,
MAX( median.median_val ) as median_item_price
FROM
sales_flat_order,
sales_flat_order_payment,
(
SELECT DATE(sq.created_at) as median_date, avg(sq.price) as median_val FROM (
SELECT t1.row_number, t1.price, t1.created_at FROM(
SELECT IF(#prev!=d.created_at, #rownum:=1, #rownum:=#rownum+1) as `row_number`, d.price, #prev:=d.created_at AS created_at
FROM sales_flat_order_item d, (SELECT #rownum:=0, #prev:=NULL) r
ORDER BY d.price
) as t1 INNER JOIN
(
SELECT count(*) as total_rows, created_at
FROM sales_flat_order_item d
GROUP BY created_at
) as t2
ON t1.created_at = t2.created_at
WHERE 1=1
AND t1.row_number>=t2.total_rows/2 and t1.row_number<=t2.total_rows/2+1
)sq
group by DATE(sq.created_at)
) as median
WHERE
sales_flat_order.status = 'complete'
AND sales_flat_order.entity_id = sales_flat_order_payment.parent_id
AND sales_flat_order_payment.method = 'checkmo'
AND median.median_date = DATE( sales_flat_order.created_at )
GROUP BY DATE( sales_flat_order.created_at )
WITH ROLLUP

How to merge the result of this 2 queries in mysql server

I am actually stuck in merging the result of this two queries:
first query:
SELECT c.code, c.name, pc.sku, pc.cat_code, pp.title
FROM `cat_parent` cp, cat c, prod_cat pc, products pp
WHERE c.code = cp.cat_code
AND cp.cat_code = pc.cat_code
AND pp.sku = pc.sku
AND cp.parent_code = 01110
AND hide =0
The result I get is:
Second query:
SELECT `sku` , `update_date` , `description` , count( * ) AS total_sold
FROM `orderline`
WHERE `update_date` >= ( DATE_ADD(CURDATE( ) , INTERVAL -14 DAY ) )
AND `update_date` <= ( DATE_ADD(CURDATE( ) , INTERVAL -7 DAY ) )
GROUP BY left( sku, 7 )
ORDER BY total_sold DESC
The result:
The question I want to ask that how can I get the result by filtering the sku available in both tables.
Just bit confused on that part....any ideas will be appreciated.
This is only part of the data. there is heaps of data. Yes, I want to merge the both tables and want to find the common sku available in both tables.
My expected result will be sku, title, total sold.
Thanks, anyway I managed to get around to get the result.
My final query:
SELECT * FROM (
SELECT sku , update_date , description FROM orderline WHERE
update_date >= '2012-03-06' AND update_date <= '2012-03-07' )g
JOIN (
SELECT c.code, c.name, pc.sku, pc.cat_code FROM cat_parent cp, cat
c, prod_cat pc, products pp WHERE c.code = cp.cat_code AND cp.cat_code
= pc.cat_code AND pp.sku = pc.sku AND cp.parent_code =01110 AND hide =0 )p ON left( g.sku, 7 ) = left( p.sku, 7 )
Something like this -
SELECT
`c`.`code`, `c`.`name`, `pc`.`sku`, `pc`.`cat_code`, `pp.title`,
`ol`.`sku`, `ol`.`update_date`, `ol`.`description`, COUNT(*) AS `total_sold`
FROM `cat_parent` `cp`
INNER JOIN `cat` `c`
ON `c`.`code` = `cp`.`cat_code`
INNER JOIN `prod_cat` `pc`
ON `cp`.`cat_code` = `pc`.`cat_code`
INNER JOIN `products` `pp`
ON `pp`.`sku` = `pc`.`sku`
INNER JOIN `orderline` `ol`
ON LEFT(`pc`.`sku`, 7) = LEFT(`ol`.`sku`, 7)
WHERE `cp`.`parent_code` = 01110
AND `hide` = 0
AND `ol`.`update_date` >= ( DATE_ADD(CURDATE( ) , INTERVAL -14 DAY ) )
AND `ol`.`update_date` <= ( DATE_ADD(CURDATE( ) , INTERVAL -7 DAY ) )
GROUP BY left( `ol`.`sku`, 7 )
ORDER BY `total_sold` DESC

Union Select Column Mismatch

Here's my query:
SELECT
FROM_UNIXTIME( date_added, '%m-%d-%Y' ) AS formatted_date,
SUM( tb =1 ) AS sum_users,
SUM( tb =2 ) AS sum_links,
SUM( tb =3 ) AS sum_ads,
SUM( tb =4 ) AS sum_actions
FROM (
SELECT date_added, 1 AS tb
FROM users_list WHERE 1=1
UNION ALL
SELECT date_added, 2
FROM users_links WHERE 1=1
UNION ALL
SELECT date_served, 3
FROM ads_served WHERE 1=1
UNION ALL
SELECT date_served, 4
FROM actions WHERE 1=1
) AS t
GROUP BY formatted_date
ORDER BY formatted_date DESC
Here's my table data:
users_list
id date_added
1 1234567890
2 1334567890
3 1434567890
users_links
id date_added
1 1244567890
2 1354567890
3 1464567890
ads_served
id date_served revenue
1 1234567891 0.01
2 1334567892 0.02
3 1434567893 0.02
actions
id date_served
1 1234561890
2 1334562890
3 1434563890
I am trying to sum the revenue for formatted_date in the ads_served table as a 6th column for the output query. I am lost as to where to start. If I add the sum(revenue) to the union select I get a "column mismatch" error.
Column revenue belongs to ads_served but you are selecting from a sub query where revenue is not present. Add it to the subquery:
SELECT
FROM_UNIXTIME( date_added, '%m-%d-%Y' ) AS formatted_date,
SUM( tb =1 ) AS sum_users,
SUM( tb =2 ) AS sum_links,
SUM( tb =3 ) AS sum_ads,
SUM( tb =4 ) AS sum_actions,
SUM( revenue ) As sum_revenue
FROM (
SELECT date_added, 1 AS tb, 0 As revenue
FROM users_list WHERE 1=1
UNION ALL
SELECT date_added, 2, 0
FROM users_links WHERE 1=1
UNION ALL
SELECT date_served, 3, revenue
FROM ads_served WHERE 1=1
UNION ALL
SELECT date_served, 4, 0
FROM actions WHERE 1=1
) AS t
GROUP BY formatted_date
ORDER BY formatted_date DESC
Try in this way. Why do you use 1=1 ?
SELECT
FROM_UNIXTIME( date_added, '%m-%d-%Y' ) AS formatted_date,
SUM( tb =1 ) AS sum_users,
SUM( tb =2 ) AS sum_links,
SUM( tb =3 ) AS sum_ads,
SUM( tb =4 ) AS sum_actions,
sum(total) as tot_rev
FROM (
SELECT date_added,'' as total, 1 AS tb
FROM users_list WHERE 1=1
UNION ALL
SELECT date_added,'', 2
FROM users_links WHERE 1=1
UNION ALL
SELECT date_served,revenue, 3
FROM ads_served WHERE 1=1
UNION ALL
SELECT date_served,'', 4
FROM actions WHERE 1=1
) AS t
GROUP BY formatted_date
ORDER BY formatted_date DESC