Reputation: 339
I have a problem and can't find a solution.
I have a simple table with TV programs, like this:
CREATE TABLE IF NOT EXISTS programs ( id_program int NOT NULL AUTO_INCREMENT PRIMARY KEY, air datetime, title varchar(50) );
and some rows in the table:
2003-10-20 17:00 Factor 2003-10-21 17:00 Factor 2003-10-22 17:00 Factor 2003-10-20 19:00 Form 2003-10-21 14:00 Factor
How can I obtain the result for Factor, something like this:
monday - wednesday : 17.00 tuesday : 14.00;
Is it possible to do this in SQL or do I need to fetch data in PHP?
Upvotes: 0
Views: 458
Reputation: 1916
This doesn't answer the question exactly as this is in MSSQL. I know there are MySQL flavors do this though
declare @tempTable TABLE (dt_timeOfProgram datetime, str_name varchar(10));
insert into @tempTable values
('2003-10-20 17:00', 'Factor'),
('2003-10-21 17:00', 'Factor'),
('2003-10-22 17:00', 'Factor'),
('2003-10-20 19:00', 'Form'),
('2003-10-21 14:00', 'Factor');
select
REPLACE(REPLACE(REPLACE(dow, '</dow><dow>', ','), '<dow>',''),'</dow>', '') as DOW
, [time]
, [showName]
from ( select distinct
CAST(dt_timeOfProgram as time) as [time],
str_name [showName],
( SELECT DATENAME(dw, t1.dt_timeOfProgram) as [dow]
FROM @tempTable t1
where t1.str_name=t2.str_name
and CAST(t1.dt_timeOfProgram as time) = CAST(t2.dt_timeOfProgram as time)
order by t1.dt_timeOfProgram
for XML PATH('')) [dow]
from @tempTable t2) as t
And here is the resultset
Tuesday 14:00:00.0000000 Factor
Monday,Tuesday,Wednesday 17:00:00.0000000 Factor
Monday 19:00:00.0000000 Form
This is pretty sloppy work though. I would never do this in a live application. This logic would be handled by business logic instead of db.
Database resources in general are the LEASE scalable. So in the end, you want to use them as little as possible.
Good Luck
Upvotes: 0
Reputation: 2759
I think to get exactly what you want in one query is not easily possible. But I came to something that is nearly your desired result:
SELECT TIME(air), title, GROUP_CONCAT(DAYOFWEEK(air))
FROM programs WHERE title = 'Factor'
GROUP BY TIME(air)
This gives me the following result:
TIME(air) title GROUP_CONCAT(DAYOFWEEK(air))
-------------------------------------------------
14:00:00 Factor 3
17:00:00 Factor 2,3,4
With this result you can easily utilize php to get your desired result. Results like "monday, wednesday, friday-saturday" are possible with this too.
Upvotes: 2