SQL make subquery of two sparate query - mysql

$sql = "SELECT max( `reg_date` ) AS endtime, min( `reg_date` ) AS starttime, sum( `distance` ) AS total FROM `user_distance` WHERE user_id =8 GROUP BY CAST( `reg_date` AS DATE )";
$sql1="SELECT CAST( `reg_date` AS DATE ) AS date, count( * ) AS customer_total FROM `customer` WHERE user_id =8 GROUP BY CAST( `reg_date` AS DATE )";
I am getting perfect result for this two queries, but I want to combine the results of this two queries.

drop temporary table if exist temp1;
create temporary table temp1
SELECT max( `reg_date` ) AS endtime, min( `reg_date` ) AS starttime, sum( `distance` ) AS total
FROM `user_distance`
WHERE user_id =8 GROUP BY CAST( `reg_date` AS DATE )"
union
SELECT CAST( `reg_date` AS DATE ) AS date,''as starttime, count( * ) AS customer_total
FROM `customer`
WHERE user_id =8 GROUP BY CAST( `reg_date` AS DATE )";
select * from temp1;

Related

How to unify two SQL queries

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

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;

Join Queries together in one

I have a two queries that I joined together with UNION ALL to do a count one for mobile leads and the other for web leads. But not exactly sure how to join the two results into one. Here is my query:
SELECT CAST( submitdate AS DATE ) as submitdate, COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS webcount FROM leads WHERE email <> '' and mobile = '0' GROUP BY CAST( submitdate AS DATE )
UNION ALL
SELECT CAST( submitdate AS DATE ) as submitdate, COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS mobilecount FROM leads WHERE email <> '' and mobile = '1' GROUP BY CAST( submitdate AS DATE )
But my results are two columns that says submitdate, webcount and the dates are duplicated and with counts next to them like this:
submitdate | webcount
2014-03-19 | 30
2014-03-19 | 15
2014-03-18 | 59
2014-03-18 | 37
When I am trying to get it to look like this:
submitdate | webcount | mobilecount
2014-03-19 | 30 | 15
2014-03-18 | 59 | 37
What am I doing wrong?
Here is a pivot approach. Use your union, but as a "PreQuery". I added one extra column to identify the origin as web or mobile by a character. From that, I use that at the outer level and do a group by date, but a sum of whatever count, but only based on the web or mobile flag value.
select
PQ.submitdate,
sum( case when PQ.leadOrigin = 'W' then PQ.DateCnt else 0 end ) as WebCount,
sum( case when PQ.leadOrigin = 'M' then PQ.DateCnt else 0 end ) as MobileCount
from
( SELECT
CAST( submitdate AS DATE ) as submitdate,
MAX( 'W' ) as leadOrigin,
COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS DateCnt
FROM
leads
WHERE
email <> ''
and mobile = '0'
GROUP BY
CAST( submitdate AS DATE )
UNION ALL
SELECT
CAST( submitdate AS DATE ) as submitdate,
MAX( 'M' ) as leadOrigin,
COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS DateCnt
FROM
leads
WHERE email <> ''
and mobile = '1'
GROUP BY CAST( submitdate AS DATE ) ) PQ
group by
PQ.submitdate
I was able to do this query:
SELECT a.submitdate, b.webcount, c.mobilecount
FROM (
SELECT DISTINCT CAST( submitdate AS DATE ) AS submitdate FROM leads) AS a
INNER JOIN
(SELECT CAST( submitdate AS DATE ) AS submitdate, COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS webcount FROM leads WHERE email <> '' AND mobile = '0' GROUP BY CAST( submitdate AS DATE )) AS b ON a.submitdate = b.submitdate
INNER JOIN
(SELECT CAST( submitdate AS DATE ) AS submitdate, COUNT( DISTINCT name, email, phone, `make` , `model` , `mdlyr` , `miles` ) AS mobilecount FROM leads WHERE email <> '' AND mobile = '1' GROUP BY CAST( submitdate AS DATE )) AS c ON b.submitdate = c.submitdate
ORDER BY a.submitdate DESC
But it only gives me dates from 3/16/2014, which is when Mobile has a count higher than 0. Is there something to add to this that will include all dates and default to 0 if there is none?

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

Sum amount of overlapping datetime ranges in MySQL

I have a question that is almost the same as Sum amount of overlapping datetime ranges in MySQL, so I'm reusing part of his text, hope that is ok...
I have a table of events, each with a StartTime and EndTime (as type DateTime) in a MySQL Table.
I'm trying to output the sum of overlapping times for each type of event and the number of events that overlapped.
What is the most efficient / simple way to perform this query in MySQL?
CREATE TABLE IF NOT EXISTS `events` (
`EventID` int(10) unsigned NOT NULL auto_increment,
`EventType` int(10) unsigned NOT NULL,
`StartTime` datetime NOT NULL,
`EndTime` datetime default NULL,
PRIMARY KEY (`EventID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=37 ;
INSERT INTO `events` (`EventID`, EventType,`StartTime`, `EndTime`) VALUES
(10001,1, '2009-02-09 03:00:00', '2009-02-09 10:00:00'),
(10002,1, '2009-02-09 05:00:00', '2009-02-09 09:00:00'),
(10003,1, '2009-02-09 07:00:00', '2009-02-09 09:00:00'),
(10004,3, '2009-02-09 11:00:00', '2009-02-09 13:00:00'),
(10005,3, '2009-02-09 12:00:00', '2009-02-09 14:00:00');
# if the query was run using the data above,
# the table below would be the desired output
# Number of Overlapped Events , The event type, | Total Amount of Time those events overlapped.
1,1, 03:00:00
2,1, 02:00:00
3,1, 02:00:00
1,3, 01:00:00
There is a really beautiful solution given there by Mark Byers and I'm wondering if that one can be extended to include "Event Type".
His solution without event type was:
SELECT `COUNT`, SEC_TO_TIME(SUM(Duration))
FROM (
SELECT
COUNT(*) AS `Count`,
UNIX_TIMESTAMP(Times2.Time) - UNIX_TIMESTAMP(Times1.Time) AS Duration
FROM (
SELECT #rownum1 := #rownum1 + 1 AS rownum, `Time`
FROM (
SELECT DISTINCT(StartTime) AS `Time` FROM events
UNION
SELECT DISTINCT(EndTime) AS `Time` FROM events
) AS AllTimes, (SELECT #rownum1 := 0) AS Rownum
ORDER BY `Time` DESC
) As Times1
JOIN (
SELECT #rownum2 := #rownum2 + 1 AS rownum, `Time`
FROM (
SELECT DISTINCT(StartTime) AS `Time` FROM events
UNION
SELECT DISTINCT(EndTime) AS `Time` FROM events
) AS AllTimes, (SELECT #rownum2 := 0) AS Rownum
ORDER BY `Time` DESC
) As Times2
ON Times1.rownum = Times2.rownum + 1
JOIN events ON Times1.Time >= events.StartTime AND Times2.Time <= events.EndTime
GROUP BY Times1.rownum
) Totals
GROUP BY `Count`
SELECT
COUNT(*) as occurrence
, sub.event_id
, SEC_TO_TIME(SUM(LEAST(e1end, e2end) - GREATEST(e1start, e2start)))) as duration
FROM
( SELECT
, e1.event_id
, UNIX_TIMESTAMP(e1.starttime) as e1start
, UNIX_TIMESTAMP(e1.endtime) as e1end
, UNIX_TIMESTAMP(e2.starttime) as e2start
, UNIX_TIMESTAMP(e2.endtime) as e2end
FROM events e1
INNER JOIN events e2
ON (e1.eventtype = e2.eventtype AND e1.id <> e2.id
AND NOT(e1.starttime > e2.endtime OR e1.endtime < e2.starttime))
) sub
GROUP BY sub.event_id
ORDER BY occurrence DESC