MySQL: Calculate the duration for multiple statuses - mysql

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

Related

Count Total from Multiple Tables

I have list table that basically contains same field on each part.
- p_ticket1_m_site_data | - p_ticket1_ticket | - p_ticket1_last_row
- p_ticket2_m_site_data | - p_ticket2_ticket | - p_ticket2_last_row
- p_ticket3_m_site_data | - p_ticket3_ticket | - p_ticket3_last_row
I can do a count on each table individually:
SELECT COUNT( * ) AS tot_sites, IFNULL( COUNT(
CASE WHEN p_ticket1_m_site_data.m_date_target = DATE( NOW( ) )
THEN 1
ELSE NULL
END ),0) AS todays_target, IFNULL( COUNT(
CASE WHEN (
p_ticket1_m_site_data.m_date_target = DATE( NOW( ) )
AND p_ticket1_ticket.t_status =9 )
THEN 1
ELSE NULL
END ),0
) AS todays_achieve, IFNULL( COUNT(
CASE WHEN p_ticket1_ticket.t_status =9
THEN 1
ELSE NULL
END ),0 ) AS tot_in
FROM p_ticket1_m_site_data
LEFT JOIN p_ticket1_last_row ON p_ticket1_last_row.t_m_id = p_ticket1_m_site_data.m_id
AND p_ticket1_last_row.t_req_type = '04_int_finish_ack'
LEFT JOIN p_ticket1_ticket ON p_ticket1_ticket.t_id = p_ticket1_last_row.t_id
WHERE p_ticket1_m_site_data.m_status =1
What should i do if i want to count all total sites from ticket1, ticket2, ticket3 ?
Please help me guys, thanks . . .
Example use UNION ALL:
I just using UNION ALL in my code above for ticket1 and ticket2, but its not what i want.
My expectation output is count all the ticket tables, so the view is tot_sites (from all ticket), todays_target(from all ticket), todays_achieve(from all ticket), and tot_in(from all ticket)
If you are sure that your tables have the same columns, you should use UNION ALL with CTE
WITH CTE AS (
SELECT *
FROM p_ticket1_m_site_data
UNION ALL
SELECT *
FROM p_ticket2_m_site_data
UNION ALL
...
)
SELECT COUNT(*), ...
FROM CTE
WHERE CTE.m_status = 1
CTE
UNION ALL
You can union the three sets of tables in a sub query and then do your counts in the main query , something like this in principal
SELECT COUNT( * ) AS tot_sites, IFNULL( COUNT(
CASE WHEN m_date_target = DATE( NOW( ) )
THEN 1
ELSE NULL
END ),0) AS todays_target, IFNULL( COUNT(
CASE WHEN (m_date_target = DATE( NOW( ) )
AND t_status =9 )
THEN 1
ELSE NULL
END ),0
) AS todays_achieve, IFNULL( COUNT(
CASE WHEN t_status =9
THEN 1
ELSE NULL
END ),0 ) AS tot_in
from
(
select *
FROM p_ticket1_m_site_data
LEFT JOIN p_ticket1_last_row ON p_ticket1_last_row.t_m_id = p_ticket1_m_site_data.m_id
AND p_ticket1_last_row.t_req_type = '04_int_finish_ack'
LEFT JOIN p_ticket1_ticket ON p_ticket1_ticket.t_id = p_ticket1_last_row.t_id
WHERE p_ticket1_m_site_data.m_status =1
union all
select *
frOM p_ticket2_m_site_data
LEFT JOIN p_ticket2_last_row ON p_ticket2_last_row.t_m_id = p_ticket2_m_site_data.m_id
AND p_ticket2_last_row.t_req_type = '04_int_finish_ack'
LEFT JOIN p_ticket2_ticket ON p_ticket2_ticket.t_id = p_ticket2_last_row.t_id
WHERE p_ticket2_m_site_data.m_status =1
union all
select *
fROM p_ticket3_m_site_data
LEFT JOIN p_ticket3_last_row ON p_ticket3_last_row.t_m_id = p_ticket3_m_site_data.m_id
AND p_ticket3_last_row.t_req_type = '04_int_finish_ack'
LEFT JOIN p_ticket3_ticket ON p_ticket3_ticket.t_id = p_ticket3_last_row.t_id
WHERE p_ticket3_m_site_data.m_status =1
) j;
Which could be tidied up. If this doesn't work for you please add sample data and expected output for your 3 tables as text to the question and I will review.

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?

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`

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

Percentages in MySQL

Using this query,
SELECT company, YEAR( date ) as year, COUNT( * ) as total
FROM table
WHERE company = "Medtronic"
OR company = "Private"
GROUP BY YEAR( date )
I get a table like this:
Company year total
Medtronic 1998 6
Private 1998 5
Medtronic 1999 5
Private 1999 1
How do I calculate the % that is contributed by each company for each year?
For example, the percentage contributed by Medtronic in year 1998 is
6 / (6+5) = 54.5%
I have been trying to make a MySQL query to calculate the percentages.
Thanks guys.
Use:
SELECT x.company,
x.year,
x.annual_total
x.annual_total / y.total AS percentage
FROM (SELECT t.company,
YEAR(t.date) as year,
COUNT( * ) as annual_total
FROM TABLE t
WHERE t.company IN ('Medtronic', 'Private')
GROUP BY YEAR( t.date ) ) x
JOIN (SELECT t.company,
COUNT(*) 'total'
FROM TABLE t
WHERE t.company IN ('Medtronic', 'Private')
GROUP BY t.company) y ON y.company = x.company
If you want the percentage with particular decimal places, use:
CAST(x.annual_total / y.total AS DECIMAL(2,2)) AS percentage
Check that this gives the count per company you expect:
SELECT t.company,
COUNT(*) 'total'
FROM TABLE t
WHERE t.company IN ('Medtronic', 'Private')
GROUP BY t.company
My SQL query:
SELECT x.company, x.year, x.annual_total, CAST( x.annual_total / y.total AS DECIMAL( 2, 2 ) ) AS percentage
FROM (
SELECT t.company, YEAR( t.date ) AS year, COUNT( * ) AS annual_total
FROM my_patents AS t
WHERE t.company = 'Private'
GROUP BY YEAR( t.date )
)x
JOIN (
SELECT t.company, COUNT( * ) AS total
FROM my_patents AS t
WHERE t.company = 'Medtronic'
OR t.company = 'Private'
GROUP BY t.company
)y ON y.company = x.company
my results:
Private 1998 5 0.04
when i run this query:
SELECT t.company, YEAR( date ) , COUNT( * ) AS total
FROM my_patents AS t
WHERE t.company = 'Medtronic'
OR t.company = 'Private'
GROUP BY t.company, YEAR( date )
I get
Medtronic 1998 6
Private 1998 5