How to unify two SQL queries - mysql

I have two SQL queries, both of them are working separately, but when I try to unify hem, I have only problems
Query 1 :
SELECT Day( funct_consumatori.timestamp ) AS numar_zi, ROUND( SUM( funct_consumatori.timp_functionare ) /3600 ) AS ore_functionare, ROUND( ROUND( SUM( funct_consumatori.timp_functionare ) /3600 ) * consumatori.kwh, 3 ) AS consum, ROUND( ROUND( ROUND( SUM( funct_consumatori.timp_functionare ) /3600 ) * consumatori.kwh, 3 ) * pret_energie.pret, 2 ) AS estimare
FROM funct_consumatori
INNER JOIN consumatori ON consumatori.id = funct_consumatori.consumator
INNER JOIN pret_energie ON pret_energie.id =1
WHERE Year( funct_consumatori.timestamp ) = Year(
CURRENT_TIMESTAMP )
AND Month( funct_consumatori.timestamp ) = Month(
CURRENT_TIMESTAMP )
GROUP BY numar_zi DESC
Query 2:
SELECT Day( ambienta.timestamp ) AS numar_zi, TRUNCATE( AVG( temperatura ) , 1 ) AS temp_med, MIN( temperatura ) AS temp_min, MAX( temperatura ) AS temp_max, TRUNCATE( AVG( umiditate ) , 1 ) AS umid_medie
FROM ambienta
INNER JOIN consumatori AS c2 ON c2.id = '1'
INNER JOIN pret_energie AS pe ON pe.id = '1'
WHERE Year( ambienta.timestamp ) = Year(
CURRENT_TIMESTAMP )
AND Month( ambienta.timestamp ) = Month(
CURRENT_TIMESTAMP )
GROUP BY numar_zi DESC
How can I unify them based on numar_zi(INNER one)?

I don't know your table and data but following SQL might work
select q1.numar_zi
,q1.ore_functionare
,q1.consum
,q1.estimare
-- value of q2 start
,q2.numar_zi
,q2.temp_med
,q2.temp_min
,q2.temp_max
,q2.umid_medie
from
(
SELECT Day( funct_consumatori.timestamp ) AS numar_zi
, ROUND( SUM( funct_consumatori.timp_functionare ) /3600 ) AS ore_functionare
, ROUND( ROUND( SUM( funct_consumatori.timp_functionare ) /3600 ) * consumatori.kwh, 3 ) AS consum
, ROUND( ROUND( ROUND( SUM( funct_consumatori.timp_functionare ) /3600 ) * consumatori.kwh, 3 ) * pret_energie.pret, 2 ) AS estimare
FROM funct_consumatori
INNER JOIN consumatori ON consumatori.id = funct_consumatori.consumator
INNER JOIN pret_energie ON pret_energie.id =1
WHERE Year( funct_consumatori.timestamp ) = Year(
CURRENT_TIMESTAMP )
AND Month( funct_consumatori.timestamp ) = Month(
CURRENT_TIMESTAMP )
GROUP BY numar_zi DESC
) q1
INNER JOIN
(
SELECT Day( ambienta.timestamp ) AS numar_zi
, TRUNCATE( AVG( temperatura ) , 1 ) AS temp_med
, MIN( temperatura ) AS temp_min
, MAX( temperatura ) AS temp_max
, TRUNCATE( AVG( umiditate ) , 1 ) AS umid_medie
FROM ambienta
INNER JOIN consumatori AS c2 ON c2.id = '1'
INNER JOIN pret_energie AS pe ON pe.id = '1'
WHERE Year( ambienta.timestamp ) = Year(
CURRENT_TIMESTAMP )
AND Month( ambienta.timestamp ) = Month(
CURRENT_TIMESTAMP )
GROUP BY numar_zi DESC
) q2
on
q1.numar_zi = q2.numar_zi
Please make the change according to your RDMS(if necessary), but remember if you want to join two query use the following query
select t1.Id, t1.Col1, t1.Col2, t2.Id, t2.Col1, t2.Col2
from
(SELECT Id, COUNT(*) AS Col1, Col2 FROM Table2 GROUP BY Id) t1
INNER JOIN -- or, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN ....
(SELECT Id, COUNT(*) AS Col1, Col2 FROM Table2 GROUP BY Id) t2
on
t1.Id= t2.Id

Related

I am missing an alias for a derived table

I know, this question has been asked very often but I know my error, I know how I could fix it, but I canĀ“t find the point where the error is. In my opinion, all the subqueries have different and unique names, I even gave the columns different names then the subqueries. Any help would be appreciated. Where is the point I am missing an alias?
Whenever I am trying to run this query I get the response "Every derived table must have its alias", which is an understandable error message, but I can't figure out where my error is located.
SELECT
mso.entity_id,
GROUP_CONCAT(msh.comment) AS comment,
msoa.lastname,
base_grand_total,
mso.created_at,
mso.status,
marketplace_order_id AS amazon_order_id,
clvData.recurrenceRate,
clvData.avgRepRate
FROM
mag_sales_flat_order AS mso
LEFT JOIN mag_sales_flat_order_status_history AS msh ON mso.entity_id = msh.parent_id
LEFT JOIN mag_sales_flat_order_address AS msoa ON mso.entity_id = msoa.parent_id
left join (
select
cast(((cet.cec - cnt.cnc) / cst.csc) AS decimal(6, 2)) as recurrenceRate,
avg(repRate.countedOrders) AS avgRepRate
from(
Select
*,
(
select
count(customer_email) AS csc
from
mag_sales_flat_order
where
created_at between '2017-01-01'
and '2017-12-31'
) AS cst,
(
select
count(customer_email) AS cec
from
mag_sales_flat_order
where
created_at between '2017-01-01'
and '2020-12-31'
) AS cet,
(
select
count(mso_new.customer_email) AS cnc
from
(
select
*
from
mag_sales_flat_order
where
created_at between '2018-01-01'
and current_date()
) AS mso_new
left join (
select
*
from
mag_sales_flat_order
where
created_at between '2017-01-01'
and '2017-12-31'
) AS mso_old on mso_new.customer_email = mso_old.customer_email
)) AS cnt
join (
select
customer_email,
count(grand_total) as countedOrders,
sum(grand_total) as summedOrders
from
mag_sales_flat_order
group by
customer_email
) AS repRate on cl.customer_email = repRate.customer_email
) AS clvData on mso.customer_email = clvData.customer_email
WHERE
store_id IN({$store['id']})
AND (
mso.status = 'complete'
OR mso.status = 'closed'
OR mso.status = 'processing'
OR mso.status = 'exported'
OR mso.status LIKE 'pending%'
)
AND (
DATE_FORMAT(mso.created_at, '%Y-%m-%d') >= '$begin_date'
)
AND (
DATE_FORMAT(mso.created_at, '%Y-%m-%d') <= '$end_date'
)
GROUP BY
entity_id;
SELECT
mso.entity_id,
GROUP_CONCAT(msh.comment) AS comment,
msoa.lastname,
base_grand_total,
mso.created_at,
mso.status,
marketplace_order_id AS amazon_order_id,
clvData.recurrenceRate,
clvData.avgRepRate
FROM mag_sales_flat_order AS mso
LEFT JOIN mag_sales_flat_order_status_history AS msh ON mso.entity_id = msh.parent_id
LEFT JOIN mag_sales_flat_order_address AS msoa ON mso.entity_id = msoa.parent_id
LEFT JOIN
(
SELECT cast(((cet.cec - cnt.cnc) / cst.csc) AS decimal(6, 2)) as recurrenceRate, avg(repRate.countedOrders) AS avgRepRate
FROM
(
SELECT *,
(
SELECT count(customer_email) AS csc
FROM mag_sales_flat_order
WHERE created_at BETWEEN '2017-01-01' AND '2017-12-31'
) AS cst,
(
SELECT count(customer_email) AS cec
FROM mag_sales_flat_order
WHERE created_at BETWEEN '2017-01-01' AND '2020-12-31'
) AS cet,
(
SELECT count(mso_new.customer_email) AS cnc
FROM
(
SELECT *
FROM mag_sales_flat_order
WHERE created_at BETWEEN '2018-01-01' AND getdate()
) AS mso_new
LEFT JOIN
(
SELECT *
FROM mag_sales_flat_order
WHERE created_at BETWEEN '2017-01-01' AND '2017-12-31'
) AS mso_old on mso_new.customer_email = mso_old.customer_email
) AS cnt
) as cl
JOIN
(
SELECT customer_email, count(grand_total) as countedOrders, sum(grand_total) as summedOrders
FROM mag_sales_flat_order
GROUP BY customer_email
) AS repRate on cl.customer_email = repRate.customer_email
) AS clvData on mso.customer_email = clvData.customer_email
WHERE store_id IN({ $ store ['id'] })
AND
(
mso.status = 'complete'
OR mso.status = 'closed'
OR mso.status = 'processing'
OR mso.status = 'exported'
OR mso.status LIKE 'pending%'
)
AND
(
DATE_FORMAT(mso.created_at, '%Y-%m-%d') >= '$begin_date'
)
AND
(
DATE_FORMAT(mso.created_at, '%Y-%m-%d') <= '$end_date'
)
GROUP BY entity_id;

Mysql query Full Join

I have three tables in my mysql db
dc_match_entries with player_id, goals, yellow cards, own goals etc for each match
dc_player player_id, team_id etc etc
dc_team team_is, some stuff etc etc
And i have this query too
SELECT
dc_player. *,
dc_team.name AS team_name,
dc_team.abbr_name AS team_abbr_name,
COUNT( dc_match_entry.player_id ) AS played,
AVG( dc_match_entry.vote ) AS vote_average,
SUM( dc_match_entry.goal ) AS goal_sum,
SUM( dc_match_entry.own_goal) AS own_goal_sum,
SUM( dc_match_entry.vote ) *10
+ SUM( dc_match_entry.goal ) *10
+ SUM( dc_match_entry.r_card ) *-10
+ SUM( dc_match_entry.y_card ) *-5
+ SUM( dc_match_entry.own_goal ) *-10 AS score,
SUM( dc_match_entry.y_card ) AS y_card_sum,
SUM( dc_match_entry.r_card ) AS r_card_sum
FROM
dc_player,
dc_match_entry,
dc_team
WHERE
dc_player.id = dc_match_entry.player_id AND
dc_player.team = dc_team.id
GROUP BY
dc_player.id
Sadly this query doesn't show players which havent played any match in the competition (since they have no dc_match_entry entries). I can't find a simple (and possibly clear) way to show those players too (full join?)
PS:
this query is nested into a bigger one :
SELECT
L.id,
L.role,
L.first_name,
L.last_name,
L.birth_date,
L.team_name,
L.team_abbr_name,
L.team AS team_id,
L.photo,
L.email,
L.played,
L.vote_average,
L.goal_sum AS goal,
L.own_goal_sum AS own_goal,
L.score +
IFNULL(L.c_mvp, 0)*15
+ IFNULL(unbeaten, 0)*50*IF(L.role='P', 1, 0) AS score,
L.y_card_sum AS y_card,
L.r_card_sum AS r_card,
IFNULL(L.c_mvp, 0) AS mvp,
IFNULL(unbeaten, 0) AS unbeaten
FROM (
SELECT * FROM (
SELECT
dc_player. *,
dc_team.name AS team_name,
dc_team.abbr_name AS team_abbr_name,
COUNT( dc_match_entry.player_id ) AS played,
AVG( dc_match_entry.vote ) AS vote_average,
SUM( dc_match_entry.goal ) AS goal_sum,
SUM( dc_match_entry.own_goal) AS own_goal_sum,
SUM( dc_match_entry.vote ) *10
+ SUM( dc_match_entry.goal ) *10
+ SUM( dc_match_entry.r_card ) *-10
+ SUM( dc_match_entry.y_card ) *-5
+ SUM( dc_match_entry.own_goal ) *-10 AS score,
SUM( dc_match_entry.y_card ) AS y_card_sum,
SUM( dc_match_entry.r_card ) AS r_card_sum
FROM
dc_player,
dc_match_entry,
dc_team
WHERE
dc_player.id = dc_match_entry.player_id AND
dc_player.team = dc_team.id
GROUP BY
dc_player.id
) LOL
LEFT JOIN (
SELECT
COUNT(dc_match.mvp) c_mvp,
mvp AS player_id
FROM dc_match
WHERE
dc_match.mvp IS NOT NULL
GROUP BY dc_match.mvp
) ROFL
ON ROFL.player_id = LOL.id
ORDER BY
LOL.score DESC
) L
LEFT OUTER JOIN(
SELECT
dc_player.id,
COUNT(dc_match.id) AS unbeaten
FROM
dc_match,
dc_match_entry,
dc_player
WHERE
(
(dc_player.team=dc_match.host AND
dc_match.guest_score=0
) OR
(
dc_player.team=dc_match.guest AND
dc_match.host_score=0
)
) AND
dc_player.id = dc_match_entry.player_id AND dc_match.id = dc_match_entry.match_id
GROUP BY
dc_player.id
) I
ON
L.id = I.id
WHERE
L.team = 2
GROUP BY
id
ORDER BY
role DESC, score DESC
You need to use a LEFT JOIN like this:
SELECT ...
FROM dc_player
JOIN dc_team ON (dc_player.team = dc_team.id)
LEFT JOIN dc_match_entry ON (dc_player.id = dc_match_entry.player_id)
GROUP BY dc_player.id
This will return a row for each player whether or not they have any match entries.

MySQL ORDER BY Aggregate column returning incorrect results

Im struggling to get this query to be able to order by stakes correctly - it returns values that are neither desc or asc. It does work with wins if I use order by. Perhaps MySQL did not evaluate the sort order at the time it was building the aggregation?
I've stripped out some of the full names to make it less tedious to read.
SELECT a.b AS t , COUNT( c.aID ) AS r ,
COUNT(
CASE WHEN c.Finish =1
THEN 1
ELSE NULL
END ) AS wins ,
CONCAT( FORMAT( (
COUNT(
CASE WHEN c.Finish =1
THEN 1
ELSE NULL
END ) / COUNT( c.aID ) ) *100, 0 ) , '%'
) AS Percent ,
FORMAT( SUM( c.StakeWon ) , 0 ) AS stakes
FROM c
INNER JOIN a ON c.aID = a.aID
INNER JOIN d ON c.dID = d.dID
WHERE d.w >= STR_TO_DATE( '2012,07,01', '%Y,%m,%d' )
AND d.w < STR_TO_DATE( '2012,07,01', '%Y,%m,%d' ) + INTERVAL 1
MONTH
GROUP BY a.b
ORDER BY stakes DESC`
It also doesnt work if I order by Percent. I didnt want to ask this question here but this is driving me crazy.
It would help if you show some of the result, but you must sort the stakes before you format it. Then you really sort the numeric value rather than the formatted string.
Here is an example SQL Fiddle how it would go wrong.
The numeric values are not sorted descending because of the formatting
100
10,000,000
-5,000,005
So you would do something like
...
FORMAT( SUM( c.StakeWon ) , 0 ) AS stakes ,
SUM( c.StakeWon ) AS stakes_num
...
ORDER BY stakes_num desc
Example how it would work: SQL Fiddle
Try using this whole expression
COUNT( c.aID ) AS r ,
COUNT(
CASE WHEN c.Finish =1
THEN 1
ELSE NULL
END ) AS wins ,
CONCAT( FORMAT( (
COUNT(
CASE WHEN c.Finish =1
THEN 1
ELSE NULL
END ) / COUNT( c.aID ) ) *100, 0 ) , '%'
) AS Percent ,
FORMAT( SUM( c.StakeWon ) , 0 )
in the order by clause instead of alias. My observation is, Alias doesn't work this way
Probably like this
SELECT a.b AS t , COUNT( c.aID ) AS r ,
COUNT(
CASE WHEN c.Finish =1
THEN 1
ELSE NULL
END ) AS wins ,
CONCAT( FORMAT( (
COUNT(
CASE WHEN c.Finish =1
THEN 1
ELSE NULL
END ) / COUNT( c.aID ) ) *100, 0 ) , '%'
) AS Percent ,
FORMAT( SUM( c.StakeWon ) , 0 ) AS stakes
FROM c
INNER JOIN a ON c.aID = a.aID
INNER JOIN d ON c.dID = d.dID
WHERE d.w >= STR_TO_DATE( '2012,07,01', '%Y,%m,%d' )
AND d.w < STR_TO_DATE( '2012,07,01', '%Y,%m,%d' ) + INTERVAL 1
MONTH
GROUP BY a.b
ORDER BY COUNT( c.aID ) AS r ,
COUNT(
CASE WHEN c.Finish =1
THEN 1
ELSE NULL
END ) AS wins ,
CONCAT( FORMAT( (
COUNT(
CASE WHEN c.Finish =1
THEN 1
ELSE NULL
END ) / COUNT( c.aID ) ) *100, 0 ) , '%'
) AS Percent ,
FORMAT( SUM( c.StakeWon ) , 0 ) DESC`

MySQL: Calculate the duration for multiple statuses

I have a database that contains member information for a club. Each member at any time can be one of three distinct statuses (active, veteran, associate). I have it broken down into three tables. The member table, with all the member information, the status table with the status_name and status_id and a grid table which includes the member_id, status_id, date_from and date_to.
I am trying to calculate the amount of time a member has spent at each status. I am currently calculating the total time that the member has spent in the "active" status via the following query:
SELECT first_name, last_name,
(DATE_FORMAT( FROM_DAYS( SUM( DATEDIFF( IFNULL( q.date_to, NOW() ) , q.date_from ) ) ) , "%Y" ) +0) as service_years
FROM member a
LEFT JOIN member_status q on a.id = q.member_id AND q.status_id = 1
GROUP BY a.id
I know that I can pull the total time that the person has been a member by leaving off the AND in the left join, however I can't figure out a way to calculate the time for each status in a single query.
My ideal result would be along the lines of:
-----------------------------------------------------------
|member_name | active_years | veteran_years | total_years |
-----------------------------------------------------------
|name | 5 | 5 | 10 |
-----------------------------------------------------------
Is there a way to accomplish what I'm looking for in a single query?
Assuming 1=active and 2=veteran, something like this should work:
SELECT first_name, last_name,
(DATE_FORMAT( FROM_DAYS( SUM( case when q.status_id = 1 then DATEDIFF( IFNULL( q.date_to, NOW() ) , q.date_from ) ) else 0 end ) , "%Y" ) +0) as active_years,
(DATE_FORMAT( FROM_DAYS( SUM( case when q.status_id = 2 then DATEDIFF( IFNULL( q.date_to, NOW() ) , q.date_from ) ) else 0 end ) , "%Y" ) +0) as veteran_years,
(DATE_FORMAT( FROM_DAYS( SUM( DATEDIFF( IFNULL( q.date_to, NOW() ) , q.date_from ) ) ) , "%Y" ) +0) as total_years
FROM member a
LEFT JOIN member_status q on a.id = q.member_id AND q.status_id in (1,2)
GROUP BY a.id
Another option is to join the member_status table more than once.
You should be able to do something like this which uses a CASE statement to determine the status name and then calculates the total number of years based on the status:
SELECT first_name,
last_name,
CASE WHEN status_name = 'active'
then (DATE_FORMAT( FROM_DAYS( SUM( DATEDIFF( IFNULL( q.date_to, NOW() ) , q.date_from ) ) ) , "%Y" ) +0) end as active_years,
CASE WHEN status_name = 'veteran'
then (DATE_FORMAT( FROM_DAYS( SUM( DATEDIFF( IFNULL( q.date_to, NOW() ) , q.date_from ) ) ) , "%Y" ) +0) end as active_years,
(DATE_FORMAT( FROM_DAYS( SUM( DATEDIFF( IFNULL( q.date_to, NOW() ) , q.date_from ) ) ) , "%Y" ) +0) as total_years,
FROM member a
LEFT JOIN member_status q
on a.id = q.member_id
AND q.status_id = 1
GROUP BY a.id, a.first_name, a.last_name
if you post some sample data it will be easier to determine the proper query

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