case when mysql with multiple conditions - mysql

I made the following case when statement in my sql:
SELECT
*,
CASE
WHEN lead_time < 14 THEN 0
WHEN (14 <= lead_time < 21 AND days_passed = 8) THEN 1
WHEN
(21 <= lead_time < 28
AND days_passed = 15)
THEN
1
WHEN
(28 <= lead_time < 42
AND days_passed = 22)
THEN
1
WHEN
(42 <= lead_time < 56
AND days_passed = 36)
THEN
1
WHEN
(56 <= lead_time < 84
AND days_passed = 29)
THEN
1
WHEN
(56 <= lead_time < 84
AND days_passed = 50)
THEN
1
WHEN (lead_time > 84 AND days_passed = 36) THEN 1
WHEN (lead_time > 84 AND days_passed = 57) THEN 1
ELSE 0
END AS send_email
I do not get any error. However, when I check the results I get:
# lead_time, days_passed, send_email
99, 15, 1
99, 22, 1
99, 15, 1
99, 8, 1
99, 8, 1
99, 8, 1
99, 8, 1
85, 29, 1
57, 50, 1
18, 36, 1
99, 22, 1
99, 22, 1
99, 22, 1
99, 22, 1
99, 22, 1
15, 15, 1
15, 15, 1
99, 8, 1
99, 8, 1
99, 8, 1
99, 8, 1
It seems as if the 'and' in the query behaves as an 'or'. Any idea why?.
Thanks,

MySQL doesn't support a syntax:
min <= expr <= max
Such kinds of expressions can be written as:
WHERE expr >= min AND expr <= max
or with using operator BETWEEN (please note that BETWEEN is inclusive):
WHERE expr BETWEEN min AND max
Comparison operators in MySQL: http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html

The comparison 14 <= lead_time < 21 AND days_passed = 8 is checked in sequence, so in a way you have:
((14 <= lead_time) < 21) AND (days_passed = 8)
Which is always true because 14 <= lead_time equals 1 and thus your comparison is equal to:
( 1 < 21 ) AND days_passed = 8
You should use a between or an and for each comparison.

Related

Mysql gaps and islands issue?

Would like to count number of rows between occurrence where total number of score is above 60, and count number of rows where this occurrence doesn't happened.
For example 5th and 6th game will end up with more then 60, so will count 5 rows with not 60 and 2 rows with 60.
I would like something like this:
type count
no-60-gap 5
yes-60-island 1
no-60-gap 3
yes-60-island 2
I have simple database of basketball games. Rough example below
id, home, score_home, away, score_away, round
1, team_1, 33, team_2, 23, 1
2, team_4, 31, team_1, 33, 1
3, team_2, 36, team_5, 53, 2
4, team_5, 35, team_1, 63, 2
5, team_7, 31, team_8, 53, 3
6, team_2, 30, team_1, 43, 3
7, team_1, 39, team_3, 13, 4
Was google-ing out this issues and I have end up trying to solve my problem with gaps and islands.
This is my solution but it not working. Idea was just to reset gap/island to 0 when it doesn't happened.
I am kind a new in this.
SET #gap :=0; SET #island :=0;
SELECT
#gap,
#island
FROM (
SELECT
CASE
WHEN (score_home + score_away) >= 60 THEN #island:=#island+1
WHEN (score_home + score_away) >= 60 THEN #gap:=0
END,
CASE
WHEN (score_home + score_away) < 60 THEN #island:=0
WHEN (score_home + score_away) < 60 THEN #gap:=#gap+1
END
FROM basket
) AS games
Appreciate any help
I suppose you're after something like this...
SELECT v,flag,COUNT(*)
FROM
( SELECT flag
, CASE WHEN #prev = flag THEN #v:=#v ELSE #v:=#v+1 END v
, #prev:=flag
FROM
( SELECT *, score_home + score_away >= 60 flag FROM my_table ) x
JOIN
( SELECT #prev:=NULL,#v:=0) vars
ORDER
BY id
) n
GROUP
BY v,flag;

How to count occurrences when the gap between the values is greater than x

Considering a simple MySQL table with a id column and a int column, I need to count how many times I have a gap equal or greater than certain value.
Let's say that value will be 10.
Given the following sample records:
{1, 2, 3} = 1 time
{1, 2, 3, 4, 5, 6, 7, 8, 9} = 1 time;
{1, 2, 3, 14, 17} = 2 times (1, 2, 3 and 14, 17);
{1, 2, 3, 14, 20, 40, 42} = 3 times (1, 2, 3 and 14, 20 and 40, 42);
Is it possible resolve that with mysql?
Yes. For table t with columns id and num this will be seems like this:
SET #n = 10;
SELECT 1 + SUM(COALESCE(t3.f, 0))
FROM (
SELECT DISTINCT t1.num, (
SELECT CASE WHEN t2.num - t1.num > #n THEN 1 ELSE 0 END
FROM t t2
WHERE t2.num > t1.num
ORDER BY num LIMIT 1
) AS f
FROM t t1
) t3

MySQL procedure while loop: Gets stuck after one iteration - Cache Clean up

There are some very large tables (TargetTable) that I am querying against, and there is a particular procedure that get stuck in its second iteration and never finishes nor crashes. The first iteration always finishes in less than a few minutes, regardless of the start of the range (loopIndex) or size of the of the range (loopStepShort).
I look forward hearing your thoughts and suggestions.
[Update 1] This problem goes away if I do one of the following:
Remove the nested part of the inner-join;
Use an in-memory temporary table for the nested part of the inner join (thanks to #SashaPachev);
Run each loop iteration outside of the while loop;
Use a smaller TargetTable.
[Update 2] Solved! I think the problem might have been occurred, when some of databases indexes were not copied on the process of database transition. Because, when I tried to reproduce an example, it was occurring for non-indexed tables (High CPU usage and virtually infinite loop step) MariaDB Server, JIRA.
The custom configurations of the MySQL InnoDB engine (10.0.21-MariaDB Server, Linux x86_64, Fedora v.21) is as the following:
innodb_buffer_pool_size = 2G
net_write_timeout = 1800
net_read_timeout = 1800
join_buffer_size = 2G
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 4M
max_allowed_packet = 4G
key_buffer = 2G
sort_buffer_size = 512K
And the procedure body is as the following:
SET loopIndex = 0;
SET loopMax = 20000000;
SET loopStepShort = 10000;
WHILE loopIndex < loopMax do
UPDATE TargetTable AS t0,
(SELECT __index, sessionStartAge
FROM SubjectTable AS t0
INNER JOIN (SELECT t0.id, t0.admission,
if(t0.startage is null and t0.endage is null, 21,
if(least(t0.startage, t0.endage) <= 1, 1,
if(least(t0.startage, t0.endage) <= 4, 2,
if(least(t0.startage, t0.endage) <= 9, 3,
if(least(t0.startage, t0.endage) <= 14, 4,
if(least(t0.startage, t0.endage) <= 19, 5,
if(least(t0.startage, t0.endage) <= 24, 6,
if(least(t0.startage, t0.endage) <= 29, 7,
if(least(t0.startage, t0.endage) <= 34, 8,
if(least(t0.startage, t0.endage) <= 39, 9,
if(least(t0.startage, t0.endage) <= 44, 10,
if(least(t0.startage, t0.endage) <= 49, 11,
if(least(t0.startage, t0.endage) <= 54, 12,
if(least(t0.startage, t0.endage) <= 59, 13,
if(least(t0.startage, t0.endage) <= 64, 14,
if(least(t0.startage, t0.endage) <= 69, 15,
if(least(t0.startage, t0.endage) <= 74, 16,
if(least(t0.startage, t0.endage) <= 79, 17,
if(least(t0.startage, t0.endage) <= 84, 18,
if(least(t0.startage, t0.endage) <= 89, 19,
if(least(t0.startage, t0.endage) <= 120, 20, 21))))))))))))))))))))) AS sessionStartAge
FROM SubjectTable AS t0
INNER JOIN ids AS t1 ON t0.id = t1.id
AND t1.id >= loopIndex
AND t1.id < (loopIndex + loopStepShort)
GROUP BY t0.id, t0.admission) AS t1
ON t0.id = t1.id AND t0.admission = t1.admission) AS t1
SET t0.sessionStartAge = t1.sessionStartAge
WHERE t0.__index = t1.__index;
SET loopIndex = loopIndex + loopStepShort;
END WHILE;
Finally, below are approximate dimensions of the tables:
TABLE: ids:
TABLE ROWS: ~1,500,000 records,
DATA LENGTH: ~250 MB,
INDEX LENGTH: ~140 MB,
TABLE SIZE: ~400 MB
TABLE: TargetTable:
TABLE ROWS: ~6,500,000 records,
DATA LENGTH: ~4 GB,
INDEX LENGTH: ~350 MB,
TABLE SIZE: ~4.35 MB
TABLE: SubjectTable:
TABLE ROWS: ~6,500,000 records,
DATA LENGTH: ~550 MB,
INDEX LENGTH: N/A,
TABLE SIZE: ~550 MB
Many thanks in advance.
I guess I have to raise a bug report to Oracle/MariaDB, and update the post.
Try this (disclaimer - untested, may contain syntax errors or bugs):
DROP TABLE IF EXISTS t1;
CREATE TEMPORARY TABLE t1 (key(id)) ENGINE=MEMORY SELECT t0.id, t0.admission,
if(t0.startage is null and t0.endage is null, 21,
if(least(t0.startage, t0.endage) <= 1, 1,
if(least(t0.startage, t0.endage) <= 4, 2,
if(least(t0.startage, t0.endage) <= 9, 3,
if(least(t0.startage, t0.endage) <= 14, 4,
if(least(t0.startage, t0.endage) <= 19, 5,
if(least(t0.startage, t0.endage) <= 24, 6,
if(least(t0.startage, t0.endage) <= 29, 7,
if(least(t0.startage, t0.endage) <= 34, 8,
if(least(t0.startage, t0.endage) <= 39, 9,
if(least(t0.startage, t0.endage) <= 44, 10,
if(least(t0.startage, t0.endage) <= 49, 11,
if(least(t0.startage, t0.endage) <= 54, 12,
if(least(t0.startage, t0.endage) <= 59, 13,
if(least(t0.startage, t0.endage) <= 64, 14,
if(least(t0.startage, t0.endage) <= 69, 15,
if(least(t0.startage, t0.endage) <= 74, 16,
if(least(t0.startage, t0.endage) <= 79, 17,
if(least(t0.startage, t0.endage) <= 84, 18,
if(least(t0.startage, t0.endage) <= 89, 19,
if(least(t0.startage, t0.endage) <= 120, 20, 21)))))))))))))))))))) as sessionStartAge,
FROM SubjectTable AS t0
INNER JOIN ids AS t1 ON t0.id = t1.id
AND t1.id >= loopIndex
AND t1.id < (loopIndex + loopStepShort)
GROUP BY t0.id, t0.admission;
UPDATE TargetTable AS t0,
(SELECT __index, sessionStartAge
FROM SubjectTable AS t0
INNER JOIN t1 ON t0.id = t1.id AND t0.admission = t1.admission) AS t2
SET t0.sessionStartAge = t1.sessionStartAge
WHERE t0.__index = t2.__index;
The idea is to replace the inner sub-query with a temporary table with a key, so that the outside join could use that key.

SQL Select Query Help. Maximum sum of consequtive four rows.

We have a traffic counter that counts cars in each lane (two inbound and two outbound) in 15 minute increments.
There is a peak period which is defined as 7:00am to 9:00am. Within this peak period we want to know the PeakHourIn and PeakHourOut and PeakHourSum.
The PeakHourIn is the highest consecutive 4x15 minute total (1 hour) for lne1in + lne4in
The PeakHourOut is the highest consecutive 4x15 minute total (1 hour) for lne2out + lne3out
The PeakHourSum is the highest consecutive 4x15 minute total (1 hour) for all lanes.
Date Time lne1in lne2out lne3out lne4in
09-18-2012 5:45 AM 2 0 0 0
09-18-2012 6:00 AM 1 0 0 1
09-18-2012 6:15 AM 2 1 0 0
09-18-2012 6:30 AM 2 1 0 0
09-18-2012 6:45 AM 6 1 2 1
09-18-2012 7:00 AM 9 1 0 3
09-18-2012 7:15 AM 81 12 22 15
09-18-2012 7:30 AM 144 31 63 56
09-18-2012 7:45 AM 84 30 62 42
09-18-2012 8:00 AM 7 1 0 3
09-18-2012 8:15 AM 11 2 3 3
09-18-2012 8:30 AM 12 3 7 1
09-18-2012 8:45 AM 16 4 8 0
09-18-2012 9:00 AM 5 2 5 0
09-18-2012 9:15 AM 10 1 4 0
Results should look like:
PeakHourIn 434
PeakHourOut 221
PeakHourSum 655
Any help would be greatly appreciated.
If you used a native temporal data type to store the date/time, you could group multiple self-joins:
SELECT MAX(lne1in + lne4in ) AS PeakHourIn,
MAX(lne2out + lne3out) AS PeakHourOut,
MAX(lne1in + lne2out + lne3out + lne4in) AS PeakHourSum
FROM (
SELECT t1.lne1in + t2.lne1in + t3.lne1in + t4.lne1in AS lne1in,
t1.lne2out + t2.lne2out + t3.lne2out + t4.lne2out AS lne2out,
t1.lne3out + t2.lne3out + t3.lne3out + t4.lne3out AS lne3out,
t1.lne4in + t2.lne4in + t3.lne4in + t4.lne4in AS lne4in
FROM my_table t1
JOIN my_table t2 ON t2.DateTime = t1.DateTime + INTERVAL 15 MINUTE
JOIN my_table t3 ON t3.DateTime = t2.DateTime + INTERVAL 15 MINUTE
JOIN my_table t4 ON t4.DateTime = t3.DateTime + INTERVAL 15 MINUTE
WHERE TIME(t1.DateTime) BETWEEN '07:00:00' AND '08:00:00'
GROUP BY t1.DateTime
) t
EDIT
Here's a solution in MySQL: http://sqlfiddle.com/#!2/ff0fb/9
create table TrafficData
(
StartTime timestamp
,Lane int
,CarCount int
);
create table LaneData
(
Lane int
, Direction bit
);
insert LaneData
select 1, 0
union select 2, 1
union select 3, 1
union select 4, 0;
insert TrafficData
select dt, lane
, case lane
when 1 then l1
when 2 then l2
when 3 then l3
when 4 then l4
else null
end
from
(
select '2012-09-18 05:45' dt, 2 l1, 0 l2, 0 l3, 0 l4
union all select '2012-09-18 06:00', 1, 0, 0, 1
union all select '2012-09-18 06:15', 2, 1, 0, 0
union all select '2012-09-18 06:30', 2, 1, 0, 0
union all select '2012-09-18 06:45', 6, 1, 2, 1
union all select '2012-09-18 07:00', 9, 1, 0, 3
union all select '2012-09-18 07:15', 81, 12, 22, 15
union all select '2012-09-18 07:30', 144, 31, 63, 56
union all select '2012-09-18 07:45', 84, 30, 62, 42
union all select '2012-09-18 08:00', 7, 1, 0, 3
union all select '2012-09-18 08:15', 11, 2, 3, 3
union all select '2012-09-18 08:30', 12, 3, 7, 1
union all select '2012-09-18 08:45', 16, 4, 8, 0
union all select '2012-09-18 09:00', 5, 2, 5, 0
union all select '2012-09-18 09:15', 10, 1, 4, 0
) as originalTable
cross join LaneData;
select Lane, max(SumCarCount) as MaxSumCarCount
from
(
select a.Lane, SUM(b.CarCount) as SumCarCount
from TrafficData a
inner join TrafficData b
on b.Lane = a.Lane
and b.StartTime between a.StartTime and DATE_ADD(DATE_ADD(a.starttime, interval 1 hour), interval -1 second)
where time(a.StartTime) between '07:00' and '08:15'
group by a.Lane, a.StartTime
) x
group by Lane
order by Lane;
select Direction, max(SumCarCount) as MaxSumCarCount
from
(
select al.Direction, SUM(b.CarCount) SumCarCount
from TrafficData a
inner join LaneData al
on al.Lane = a.Lane
inner join TrafficData b
on b.StartTime between a.StartTime and DATE_ADD(DATE_ADD(a.starttime, interval 1 hour), interval -1 second)
inner join LaneData bl
on bl.Lane = b.Lane
and bl.Direction = al.Direction
where time(a.StartTime) between '07:00' and '08:15'
group by al.Direction, a.StartTime
) x
group by Direction
order by Direction;
ORIGINAL
Here's how I'd go about it in SQL Server:
--I'd change your table structure to be like this - that way you can easily add new lanes without rewriting the whole system
declare #trafficData table
(
StartTime DateTime
,Lane int
,CarCount int
)
--here's where you store additional info about the lanes (e.g. what direction they go in)
declare #laneData table
(
Lane int
, Direction bit --0 in, 1 out
)
--populate the tables with sample data
insert #laneData
select 1, 0
union select 2, 1
union select 3, 1
union select 4, 0
insert #trafficData
select dt, lane
, case lane
when 1 then l1
when 2 then l2
when 3 then l3
when 4 then l4
else null --should never happen
end
from
(
select '2012-09-18 5:45 AM' dt, 2 l1, 0 l2, 0 l3, 0 l4
union all select '2012-09-18 6:00 AM', 1, 0, 0, 1
union all select '2012-09-18 6:15 AM', 2, 1, 0, 0
union all select '2012-09-18 6:30 AM', 2, 1, 0, 0
union all select '2012-09-18 6:45 AM', 6, 1, 2, 1
union all select '2012-09-18 7:00 AM', 9, 1, 0, 3
union all select '2012-09-18 7:15 AM', 81, 12, 22, 15
union all select '2012-09-18 7:30 AM', 144, 31, 63, 56
union all select '2012-09-18 7:45 AM', 84, 30, 62, 42
union all select '2012-09-18 8:00 AM', 7, 1, 0, 3
union all select '2012-09-18 8:15 AM', 11, 2, 3, 3
union all select '2012-09-18 8:30 AM', 12, 3, 7, 1
union all select '2012-09-18 8:45 AM', 16, 4, 8, 0
union all select '2012-09-18 9:00 AM', 5, 2, 5, 0
union all select '2012-09-18 9:15 AM', 10, 1, 4, 0
) originalTable
cross join #laneData
--peak for each individual lane
select *
from
(
select a.Lane, a.StartTime, SUM(b.CarCount) SumCarCount
, ROW_NUMBER() over (partition by a.lane order by SUM(b.CarCount) desc) r
from #trafficData a
inner join #trafficData b
on b.Lane = a.Lane
and b.StartTime between a.StartTime and DATEADD(second,-1,DATEADD(hour,1,a.starttime))
group by a.Lane, a.StartTime
) x
where r = 1
order by Lane
--peak for lane direction
select *
from
(
select al.Direction, a.StartTime, SUM(b.CarCount) SumCarCount
, ROW_NUMBER() over (partition by al.Direction order by SUM(b.CarCount) desc) r
from #trafficData a
inner join #laneData al
on al.Lane = a.Lane
inner join #trafficData b
on b.StartTime between a.StartTime and DATEADD(second,-1,DATEADD(hour,1,a.starttime))
inner join #laneData bl
on bl.Lane = b.Lane
and bl.Direction = al.Direction
group by al.Direction, a.StartTime
) x
where r = 1
order by Direction

Calculate values in ranges for every row in table

I have table where some objects are described.
id title low middle high
-- ------- --- ------ ----
1 Object1 2 5 11
2 Object2 2 6 11
3 Object3 2 5 15
4 Object4 2 5 11
5 Object5 2 5 11
6 Object6 2 5 11
7 Object7 2 5 15
So for Object1 values 0…2 should be calculated as lowCount , 3…5 as middleCount, 6…11 as highCount, all values greater than 11 as overCount.
Every object could get 3 values and it’s necessary to count how many values are in low, medium, high and over ranges
So For example with values 1, 4, 12 I expect to get the result
id title low middle high lowCount middleCount highCount overCount
-- ------- --- ------ ---- -------- ----------- --------- ---------
1 Object1 2 5 11 1 0 1 1
2 Object2 2 6 11 1 1 0 1
3 Object3 2 5 15 1 0 2 0
4 Object4 2 5 11 1 0 1 1
5 Object5 2 5 11 1 0 1 1
6 Object6 2 5 11 1 0 1 1
7 Object7 2 5 15 1 0 2 0
For this issue I use the query:
SELECT
`st`.`id`, `st`.`title`, `st`.`low`, `st`.`middle`, `st`.`high`
, (IF((1 >= 0 AND 1 <= `st`.`low`), 1, 0) + IF((4 >= 0 AND 4 <= `st`.`low`), 1, 0) + IF((12 >= 0 AND 12 <= `st`.`low`), 1, 0)) as `lowCount`
, (IF((1 > `st`.`low` AND 1 <= `st`.`middle`), 1, 0) + IF((4 > `st`.`low` AND 4 <= `st`.`middle`), 1, 0) + IF((12 > `st`.`low` AND 12 <= `st`.`middle`), 1, 0)) as `middleCount`
, (IF((1 > `st`.`middle` AND 1 <= `st`.`high`), 1, 0) + IF((4 > `st`.`middle` AND 4 <= `st`.`high`), 1, 0) + IF((12 > `st`.`middle` AND 12 <= `st`.`high`), 1, 0)) as `highCount`
, (IF((1 > `st`.`high`), 1, 0) + IF((4 > `st`.`high`), 1, 0) + IF((12 > `st`.`high`), 1, 0)) + 2 as `overCount`
FROM
`some_table` `st`
I don't like this construction
, (IF((1 >= 0 AND 1 <= `st`.`low`), 1, 0) + IF((4 >= 0 AND 4 <= `st`.`low`), 1, 0) + IF((12 >= 0 AND 12 <= `st`.`low`), 1, 0)) as `lowCount`
What could I use instead
if is acceptable. The case statement is longer, but standard SQL. However, in MySQL, you can also do:
select `st`.`id`, `st`.`title`, `st`.`low`, `st`.`middle`, `st`.`high`,
((1 >= 0 AND 1 <= `st`.`low`) + (4 >= 0 AND 4 <= `st`.`low`) + (12 >= 0 AND 12 <= `st`.`low`)) as `lowCount`,
((1 > `st`.`low` AND 1 <= `st`.`middle`) + (4 > `st`.`low` AND 4 <= `st`.`middle`) + (12 > `st`.`low` AND 12 <= `st`.`middle`)) as `middleCount`,
((1 > `st`.`middle` AND 1 <= `st`.`high`) + (4 > `st`.`middle` AND 4 <= `st`.`high`) + (12 > `st`.`middle` AND 12 <= `st`.`high`)) as `highCount`
FROM `some_table` `st`;
In other words, MySQL treats "true" as 1 and "false" as 0, so you can just add up the boolean values to get the counts.