This question already has an answer here:
I have a table something like this:
Lecture_ID | Subject | Section | time_Date
0001 | Maths | A | ....
0002 | Maths | B | ....
0003 | Maths | C | ....
0004 | Maths | B | ....
I want that the data should be grouped by section so that when i echo
out the data, it should be something like this:
Section A
time_Date
time_Date
Section B
time_Date
time_Date
...
How can i achieve a query to do something like this..All i have is like
$query = 'SELECT * FROM Lecutre_info WHERE Subject="'.$_GET['subject'].'" ORDER BY Section ASC';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
print '<h1>'.$row['Section']
print '<br>'.$row['time_Date'];
}
You can imagine that i have the Section
with every record. How can i group the entries together. Also i dont know how many section there will be beforehand and sections could start from any alphabet and not necessarily 'A'. So e.g. there could be a Science class with 1 section named X. Thanks...
</div>
The following sql will output to what you want:
see fiddle: http://sqlfiddle.com/#!2/ea7f7b/21/0
select case when length(section) = 1 then
concat('Section ',section)
else substring_index(section, '/', -1)
end as result
from (select distinct section
from tbl
union all
select concat(section, '/', dt)
from tbl
order by 1) x
Often, this type of data transform is done on the application side. You can get the data into this format. The challenge is getting the extra rows for section and putting two different types in the same column (a datetime and a string). You can do ti as:
select (case when time_date is null then section
else date_format(time_date, YOURFORMATHERE )
end)
from ((select section, time_date from lecture_info li) union all
(select distinct section, NULL)
) t
order by section,
time_date is null desc,
time_date;