Result in row mysql - mysql

i have this data on my table
ID DATE TIME STATE SIP
'1', '2017-10-31', '10:24:51', 'R', '237'
'2', '2017-10-31', '10:41:35', 'U', '237'
'3', '2017-10-31', '10:45:32', 'R', '611'
'4', '2017-10-31', '10:45:40', 'U', '611'
'5', '2017-10-31', '10:46:03', 'R', '258'
'6', '2017-10-31', '11:10:51', 'R', '237'
'7', '2017-10-31', '11:17:03', 'R', '611'
'8', '2017-10-31', '11:32:21', 'U', '611'
'9', '2017-10-31', '11:32:37', 'R', '611'
'10', '2017-10-31', '11:53:06', 'R', '258'
'11', '2017-10-31', '12:01:24', 'R', '252'
'12', '2017-10-31', '12:01:36', 'U', '611'
'13', '2017-10-31', '12:01:43', 'R', '617'
'14', '2017-10-31', '12:01:57', 'U', '258'
'15', '2017-10-31', '12:02:24', 'R', '611'
'16', '2017-10-31', '12:02:39', 'R', '258'
'17', '2017-10-31', '12:29:09', 'U', '611'
'18', '2017-10-31', '12:31:30', 'R', '611'
'19', '2017-10-31', '12:55:58', 'R', '237'
'20', '2017-10-31', '12:59:58', 'U', '611'
'21', '2017-10-31', '13:00:16', 'U', '252'
'22', '2017-10-31', '13:00:17', 'U', '237'
This is my recordset,
i would like to calculate how much time the SIP stay register on system.
state R=Registered U=Unregistered but i don't have a regular login and logout
i would like have:
SIP DATE LOGIN LOGOUT
237 2017-10-31 10:24:51 10:41:35
611 2017-10-31 10:45:32 10:45:40
258 2017-10-31 10:46:03 12:01:57
and calculate the total time stay connected
thank you for the time you have dedicated to me

Following solution will work:
select sip,
min(time) as login,
(case when max(time)=min(time) then 'lost'
else max(time)
end
) as logout
from SIPregistration
where time between '10:00:00' and '11:00:00'
and state in('R','U')
group by sip;
You can put the text after THEN with whatever you want to display in case of there is no logout by an sip.
Click here for the DEMO

Looks like you want result overlap your range.
First create the SIP ranges:
SELECT s1.sip,
s1.time as login
s2.time as logout
COALESCE(s2.time, NOW()) as not_null_logout
FROM SIPregistration s1
LEFT JOIN SIPregistration s2 -- I assume there are some SIP without logout
ON s1.soip =s2.sip
AND s1.time > s2.time
-- WHERE s2.time IS NOT NULL -- optional
Now found out if the SIP range overlap with your time window
SELECT s1.sip,
s1.time as login
s2.time as logout
FROM SIPregistration s1
LEFT JOIN SIPregistration s2
ON s1.soip =s2.sip
AND s1.time > s2.time
WHERE s1.time < '11:00:00'
AND s2.time > '10:00:00' -- sip without logout wont show becasue s2.time is NULL.

The final query should look like this:
SELECT sip, `date`
min(time) as login,
IF(max(time) != min(time), max(time), 'Not Logged Yet In This Range') as logout,
IF(max(time) != min(time), TIMEDIFF(max(time), min(time)), 'Not Logged Yet In This Range') as connected
From words
WHERE time between '10:00:00' and '11:00:00'
GROUP BY sip;
You can change the text in if clause with what you want.
We just check if the max of time equal the min in the specific range you have in where clause
IF(expression ,expr_true, expr_false);
DATEDIFF(interval, date1, date2); the interval not required

Related

SQL query to get number of clients with last statement equal connected

I need to make a SQL query
table 'records' structure:
contact_id(integer),
client_id(integer),
worker_id(integer),
statement_status(varchar),
contact_ts(timestamp)
It has to show the following:
current date
number of clients which last statement_status was 'interested'
number of clients which last statement_status was 'not_interested' and previus status was 'not_present'
Could somebody help?
sample data:
contact_id client_id contact_ts worker_id statement_status
'1', '181', '2017-09-24 03:38:31.000000', '107', 'voicemail'
'2', '72', '2017-09-23 09:32:38.000000', '10', 'not_interested'
'3', '277', '2017-09-22 07:06:16.000000', '119', 'interested'
'4', '36', '2017-09-21 04:39:57.000000', '118', 'not_present'
'5', '33', '2017-09-20 04:12:12.000000', '161', 'voicemail'
'6', '244', '2017-09-19 02:26:30.000000', '13', 'not_interested'
'7', '346', '2017-09-18 02:30:35.000000', '255', 'interested'
'8', '128', '2017-09-17 06:20:13.000000', '52', 'not_present'
'9', '33', '2017-09-16 08:58:02.000000', '188', 'not_present'
'10', '352', '2017-09-15 08:18:40.000000', '324', 'not_interested'
'11', '334', '2017-09-14 04:27:40.000000', '373', 'interested'
'12', '2', '2017-09-13 08:44:40.000000', '40', 'not_present'
'13', '33', '2017-09-12 03:46:16.000000', '252', 'voicemail'
'14', '366', '2017-09-11 04:31:22.000000', '78', 'not_interested'
'15', '184', '2017-09-10 06:08:01.000000', '289', 'interested'
'16', '184', '2017-09-09 05:45:56.000000', '124', 'not_present'
'17', '102', '2017-09-08 07:09:30.000000', '215', 'voicemail'
'18', '140', '2017-09-07 08:09:18.000000', '196', 'not_interested'
'19', '315', '2017-09-06 05:13:40.000000', '242', 'interested'
'20', '268', '2017-09-05 07:41:40.000000', '351', 'not_present'
'21', '89', '2017-09-04 05:32:05.000000', '232', 'voicemail'
desired output:
Time, interested, not-interested
2017-09-10 06:08:01, 5, 5
I tried something with sub queries, but it obviously doesn't work:
SELECT
GETDATE()
,(select count(*)
from record a
where (select statement_status
from record
where client_id == a.client_id
order by a.contact_ts
limit 1) == "interested"
group by a.contact_id)
,(select count(*)
from record a
where (select (select statement_status
from record
where client_id == a.client_id
order by a.contact_ts
limit 2) order by a.contact_ts desc limit 1) == "interested"
and
(select statement_status
from record
where client_id == a.client_id
order by a.contact_ts
limit 1) == "interested"
group by a.contact_id)
from record b;
How should I use the inner selects?
I must write a poem, because most of my post is a code.
So maybe something from "Dead man"?
“Don't let the sun burn a hole in your ass, William Blake. Rise now, and drive your cart and plough over the bones of the dead!”
;)
Try something like this:
WITH status AS (
SELECT DISTINCT client_id,
first_value(statement_status) OVER w1 AS last_status,
nth_value(statement_status, 2) OVER w1 AS prev_status
FROM records
WINDOW w1 AS (PARTITION BY client_id ORDER BY contact_ts DESC RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
)
SELECT CURRENT_DATE(),
SUM(last_status = 'interested') AS interesed,
SUM(last_status = 'not_interested' AND prev_status = 'not_present') AS not_interested
FROM status

Changing multiple rows to columns (Pivotable) in a table from mysql [duplicate]

Hi i have the following mysql data
INSERT INTO `monthly` (`id`, `year`, `stat_id`, `cat_id`, `January`, `February`, `March`, `April`, `May`, `June`, `July`, `August`, `September`, `October`, `November`, `December`) VALUES
(1, '2017', '12', '25', '1', '3', '1', '1', '3', '4', '4', '2', '4', '', '', ''),
and i would like it to be convert to be like this
INSERT INTO `monthlydata` (`id`, `year`, `monthName`, `stat_id`, `cat_id`, `data`) VALUES
(1, '2017', 'January', '12', '25', '1'),
(2, '2017', 'February', '12', '25', '3'),
(3, '2017', 'March', '12', '25', '1'),
(4, '2017', 'April', '12', '25', '1'),
(5, '2017', 'May', '12', '25', '3'),
(6, '2017', 'June', '12', '25', '4'),
(7, '2017', 'July', '12', '25', '4'),
(8, '2017', 'August', '12', '25', '2'),
(9, '2017', 'September', '12', '25', '4'),
(10, '2017', 'October', '12', '25', ''),
(11, '2017', 'November', '12', '25', ''),
(12, '2017', 'December', '12', '25', ''),
is there an easier way to do this using mysql/php
You need to UNPIVOT your data. MySQL doesn't have a built in function to do that so you'll need to use multiple queries.
INSERT INTO `monthlydata` (`id`, `year`, `monthName`, `stat_id`, `cat_id`, `data`) VALUES
SELECT id, year, 'January', stat_id, cat_id, January
FROM monthly WHERE monthName = 'January'
UNION ALL
SELECT id, year, 'February', stat_id, cat_id, February
FROM monthly WHERE monthName = 'February'
UNION ALL
SELECT id, year, 'March', stat_id, cat_id, March
FROM monthly WHERE monthName = 'March'
.....
ID column here might cause issues. Depending on how you have defined it. If it is auto generated then you can remove it from the INSERT and let it be auto generated. Since you'll have rows for all months with same ID, you need to handle that scenario.

MySQL count(*) returning 0 even though I used IFNULL and COALESCE

Here is my query:
USE adventureWorks4mysql;
SELECT DISTINCT a.city, count(a.city) as "City Count", emp.Gender as Gender, emp.VacationHours as VacationHours,
(select if(count(*) is null,0, count(*))
FROM address aa
inner join employeeaddress empad on aa.AddressID = empad.AddressID
inner join employee emp on empad.EmployeeID = emp.EmployeeID
where MaritalStatus = 'M' and aa.city = a.city
group by aa.City) as married,
(select ifnull(count(*),0)
FROM address aa
inner join employeeaddress empad on aa.AddressID = empad.AddressID
inner join employee emp on empad.EmployeeID = emp.EmployeeID
where MaritalStatus = 'S' and aa.city = a.city
group by aa.City) as single
FROM address a
inner join employeeaddress empad on a.AddressID = empad.AddressID
inner join employee emp on empad.EmployeeID = emp.EmployeeID
group by a.City;
returns the following:
'Bellevue', '36', 'F', '5', '22', '14'
'Berlin', '1', 'F', '35', NULL, '1'
'Bordeaux', '1', 'M', '34', NULL, '1'
'Bothell', '13', 'M', '9', '7', '6'
'Calgary', '1', 'M', '33', '1', NULL
'Cambridge', '2', 'F', '37', '2', NULL
'Carnation', '5', 'M', '77', '4', '1'
'Detroit', '1', 'M', '38', NULL, '1'
'Duluth', '1', 'F', '24', NULL, '1'
'Duvall', '10', 'F', '80', '3', '7'
'Edmonds', '25', 'M', '84', '16', '9'
'Everett', '18', 'M', '42', '11', '7'
'Gold Bar', '5', 'M', '92', '3', '2'
'Index', '5', 'F', '61', '3', '2'
'Issaquah', '15', 'M', '70', '4', '11'
'Kenmore', '12', 'F', '86', '5', '7'
'Kent', '1', 'F', '5', '1', NULL
'Melbourne', '1', 'F', '36', NULL, '1'
'Memphis', '1', 'M', '29', '1', NULL
'Minneapolis', '1', 'M', '48', NULL, '1'
'Monroe', '14', 'M', '21', '4', '10'
'Nevada', '1', 'F', '27', '1', NULL
'Newport Hills', '7', 'M', '44', '2', '5'
'Ottawa', '1', 'M', '31', '1', NULL
'Portland', '1', 'F', '22', NULL, '1'
'Redmond', '21', 'M', '2', '11', '10'
'Renton', '17', 'M', '6', '12', '5'
'Sammamish', '17', 'F', '31', '6', '11'
'San Francisco', '2', 'M', '16', '2', NULL
'Seattle', '44', 'F', '82', '21', '23'
'Snohomish', '10', 'M', '88', '3', '7'
Not at all clear about you desired result, but is you are attempting to count cities, then I suggest you use "conditional aggregates" instead of your current approach, like this:
SELECT
a.city
, COUNT( a.city ) AS "City Count"
, count(CASE WHEN maritalstatus = 'M' THEN a.city END) AS married
, count(CASE WHEN maritalstatus = 'S' THEN a.city END) AS single
FROM address a
INNER JOIN employeeaddress empad ON a.addressid = empad.addressid
INNER JOIN employee emp ON empad.employeeid = emp.employeeid
GROUP BY
a.city;
Note how the case expression is INSIDE the aggregate function COUNT - hence the term "conditional aggregates" e.g. for singles, if there is a singe status then count that address other wise just ignore that row. nb COUNT does not increment if a value is null.
Please also note that you are only grouping by the single column city. If you really want more result rows because of gender and vacationhours then also use those columns in the GROUP BY clause
SELECT
a.city
, emp.gender AS Gender
, emp.vacationhours AS VacationHours
, COUNT( a.city ) AS "City Count"
, count(CASE WHEN maritalstatus = 'M' THEN a.city END) AS married
, count(CASE WHEN maritalstatus = 'S' THEN a.city END) AS single
FROM address a
INNER JOIN employeeaddress empad ON a.addressid = empad.addressid
INNER JOIN employee emp ON empad.employeeid = emp.employeeid
GROUP BY
a.city
, emp.gender
, emp.vacationhours
;

Rank by calculated variable in MySQL

The following table is for practice only. I will use the code on a much larger table.
SELECT *
FROM price_practice;
gives
id company dt price
'16', 'Amex', '2015-07-01', '5.00'
'17', 'Amex', '2015-07-02', '5.10'
'18', 'Amex', '2015-07-03', '5.00'
'19', 'Amex', '2015-07-06', '5.88'
'20', 'Amex', '2015-07-07', '4.21'
'21', 'Citi', '2015-07-01', '1.00'
'22', 'Citi', '2015-07-02', '1.10'
'23', 'Citi', '2015-07-03', '1.00'
'24', 'Citi', '2015-07-06', '0.88'
'25', 'Citi', '2015-07-07', '1.01'
'26', 'Amex', '2015-07-08', '5.23'
'27', 'Amex', '2015-07-09', '5.35'
'28', 'Amex', '2015-07-10', '5.55'
'29', 'Amex', '2015-07-13', '5.88'
'30', 'Amex', '2015-07-14', '6.01'
'31', 'Citi', '2015-07-08', '0.95'
'32', 'Citi', '2015-07-09', '0.83'
'33', 'Citi', '2015-07-10', '0.79'
'34', 'Citi', '2015-07-13', '0.72'
'35', 'Citi', '2015-07-14', '0.59'
The following snippet calculates the percentage change in price from one date to the next.
SELECT x.id, x.company, x.dt, x.price, (x.price - y.price)/y.price AS 'Change'
FROM
(
SELECT a.id AS aid, MAX(b.id) AS aPrevid
FROM price_practice a
INNER JOIN price_practice b
WHERE a.id > b.id
AND a.company = b.company
GROUP BY a.id
) Sub1
INNER JOIN price_practice x ON Sub1.aid = x.id
INNER JOIN price_practice y ON Sub1.aPrevid = y.id
ORDER BY x.id DESC
As intended, it returns
id company dt price Change
'35', 'Citi', '2015-07-14', '0.59', '-0.180556'
'34', 'Citi', '2015-07-13', '0.72', '-0.088608'
'33', 'Citi', '2015-07-10', '0.79', '-0.048193'
'32', 'Citi', '2015-07-09', '0.83', '-0.126316'
'31', 'Citi', '2015-07-08', '0.95', '-0.059406'
'30', 'Amex', '2015-07-14', '6.01', '0.022109'
'29', 'Amex', '2015-07-13', '5.88', '0.059459'
'28', 'Amex', '2015-07-10', '5.55', '0.037383'
'27', 'Amex', '2015-07-09', '5.35', '0.022945'
'26', 'Amex', '2015-07-08', '5.23', '0.242280'
'25', 'Citi', '2015-07-07', '1.01', '0.147727'
'24', 'Citi', '2015-07-06', '0.88', '-0.120000'
'23', 'Citi', '2015-07-03', '1.00', '-0.090909'
'22', 'Citi', '2015-07-02', '1.10', '0.100000'
'20', 'Amex', '2015-07-07', '4.21', '-0.284014'
'19', 'Amex', '2015-07-06', '5.88', '0.176000'
'18', 'Amex', '2015-07-03', '5.00', '-0.019608'
'17', 'Amex', '2015-07-02', '5.10', '0.020000'
The following snippet does something entirely different: it ranks observations by price for every company seperately.
SELECT (
CASE company
WHEN #curType
THEN #curRow := #curRow + 1
ELSE #curRow := 1 AND #curType := company END
) + 1 AS rank,
id,
company,
dt,
price
FROM price_practice,
(SELECT #curRow := 0, #curType := '') r
ORDER BY company DESC, price DESC;
As intended, it returns
rank id company dt price
'1', '22', 'Citi', '2015-07-02', '1.10'
'2', '25', 'Citi', '2015-07-07', '1.01'
'3', '23', 'Citi', '2015-07-03', '1.00'
'4', '21', 'Citi', '2015-07-01', '1.00'
'5', '31', 'Citi', '2015-07-08', '0.95'
'6', '24', 'Citi', '2015-07-06', '0.88'
'7', '32', 'Citi', '2015-07-09', '0.83'
'8', '33', 'Citi', '2015-07-10', '0.79'
'9', '34', 'Citi', '2015-07-13', '0.72'
'10', '35', 'Citi', '2015-07-14', '0.59'
'1', '30', 'Amex', '2015-07-14', '6.01'
'2', '19', 'Amex', '2015-07-06', '5.88'
'3', '29', 'Amex', '2015-07-13', '5.88'
'4', '28', 'Amex', '2015-07-10', '5.55'
'5', '27', 'Amex', '2015-07-09', '5.35'
'6', '26', 'Amex', '2015-07-08', '5.23'
'7', '17', 'Amex', '2015-07-02', '5.10'
'8', '18', 'Amex', '2015-07-03', '5.00'
'9', '16', 'Amex', '2015-07-01', '5.00'
'10', '20', 'Amex', '2015-07-07', '4.21'
The question is:
How do I rank observations by percentage change?
I imagine you can save the percentage change data in a new column and then rank it, but I suspect this is not the best method. I will do many similar calculations (eg weekly % change, variance etc), and I have around 3,000,000 observations, so the table would grow big quickly. If this is the only way to do it, I will, but I think combining the two snippets above to calculate percentage change and rank in one go would be better. Or what do you think?
As I'm sure you can tell from my question, I'm a beginner at MySQL. Any advise on how to proceed is appreciated!

SQL query to show top x records with evenly distributed values

I have a database of contacts at companies. Multiple contacts per company in different departments. Each company has turnover and industry data attached to it.
I need to write a query that shows the top 10 most recently added contacts (unix timestamp) but i don't want it to be all Marketing contacts (even if the top 10 are), i would like to look at the top 100 instead and get 10 contacts out that are from different departments. So instead of the top 10 being all marketing, there might be 2 marketing, 2 I.T, 2 HR, 2 Personnel.
So my query basically is this:
SELECT DISTINCT `surname`, `job_title`, `company_name`
FROM (`company_database`)
WHERE `employee_code` IN ('6', '7', '8', '9', '10', '11', '12', '13')
AND `turnover_code` IN ('5', '6', '7', '8')
AND `contact_code` IN ('16', '17', '26', '27', '9', '10', '30', '31', '23', '24', '12', '13') AND `industry_code` NOT IN ('22', '17', '35', '36') LIMIT 10
But that simply returns a unique row. What i need is one contact per company and no more than 1 contact_code type. I also only want 10 rows returned, but obviously to get this 1 per contact code per row, the query will need to look at more than 10.
Is this possible in just a query? Or should i do something programatically to apply the logic needed to whittle down the results of a query.
you can work with a temporary table using the myisam engine and a trick.
If you create the following temporary table:
create table tmp_company_sequence
( surname varchar(255)
,job_title varchar(255)
,company_name varchar(255)
,date_added date
,contact_code int
,counter int auto_increment
,primary key (contact_code,counter)
);
Now
insert into `tmp_company_sequence`( `surname`, `job_title`, `company_name`,`contact_code`,`date_added`)
SELECT DISTINCT `surname`, `job_title`, `company_name`,`contact_code`,`date_added`
FROM (`company_database`)
WHERE `employee_code` IN ('6', '7', '8', '9', '10', '11', '12', '13')
AND `turnover_code` IN ('5', '6', '7', '8')
AND `contact_code` IN ('16', '17', '26', '27', '9', '10', '30', '31', '23', '24', '12', '13') AND `industry_code` NOT IN ('22', '17', '35', '36')
order by contact_code, added_date desc;
Your temporary table will now hold all the contacts with a counter. The counter is increased for every contact of the same contact_code. SO the newest contact with a certain contact code will have counter = 1, the next recent will have counter = 2 and so on.
You can now do a
select *
from tmp_company_sequence
order by counter asc, date_added desc
limit 10;
This will give you a list of the latest contacts added over all contact_codes.
Edit:
I just realised this could be done with a single query, but it is even more ugly:
SELECT `surname`
, `job_title`
, `company_name`
, `contact_code`
FROM(
SELECT
`surname`
, `job_title`
, `company_name`
, `contact_code`
, `date_added`
, IF(contact_code = #prev_contact_code,#i:=#i+1,#i:=1) AS counter
, #prev_contact_code = contact_code
FROM
(`company_database`)
,(SELECT #i := 1)
WHERE `employee_code` IN ('6', '7', '8', '9', '10', '11', '12', '13')
AND `turnover_code` IN ('5', '6', '7', '8')
AND `contact_code` IN (
'16'
, '17'
, '26'
, '27'
, '9'
, '10'
, '30'
, '31'
, '23'
, '24'
, '12'
, '13'
)
AND `industry_code` NOT IN ('22', '17', '35', '36')
ORDER BY contact_code
, added_date DESC) sub
WHERE counter = 1
ORDER BY added_date DESC
LIMIT 10;
This does basically the same as the option with the temporary table, but it creates the counter in the fly by storing data from the previous column in global variables. It is messy but can be used within a single query.