I have an application that has several stores, and each store has several records in store_hours.
The store_hours table looks like this:
store_id [int]
day [varchar(20)]
opening_time [varchar(20)]
closing_time [varchar(20)]
and the records for one store may look like this:
301, 'Monday', '7am', '8:30pm'
301, 'Tuesday', '7am', '8:30pm'
301, 'Wednesday', '7am', '8:30pm'
301, 'Thursday', '7am', '8:30pm'
301, 'Friday', '7am', '10pm'
301, 'Saturday', 'closed,' 'closed'
301, 'Sunday', 'closed,' 'closed'
We’re trying to make an “hours summary” column on the store table. The above query would result in something like ‘M: 7am-8:30pm, T: 7am-8:30pm, W: 7am-8:30pm, T: 7am-8:30pm, F: 7am-8:30pm, S: closed, S: closed’
I’m populating it by running a query similar to this:
UPDATE s
SET hours_summary =
'M: ' + (SELECT TOP 1 ch.opening_time FROM store_hours ch WHERE c.id = ch.store AND [day] = 'Monday') + '-' + (SELECT TOP 1 ch.closing_time FROM store_hours ch WHERE c.id = ch.store AND [day] = 'Monday') + ', ' +
'T: ' + (SELECT TOP 1 ch.opening_time FROM store_hours ch WHERE c.id = ch.store AND [day] = 'Tuesday') + '-' + (SELECT TOP 1 ch.closing_time FROM store_hours ch WHERE c.id = ch.store AND [day] = 'Tuesday') + ', '
(etc, for the other five days)
FROM stores s
Now, this will work (more or less), but I have a couple questions.
- This is ugly, in my opinion, and seems to have a lot of repetion. Is there anyway you can think of to improve it?
- For some records, if the store is closed, there is no record at all in the store_hours table. I haven’t come up with a good way to handle this. Suggestions?
EDIT
Several people have recommended using a pivot table. I see how I can get the opening or closing time in there, but I don’t see how I can do both, and I don’t see how I can summarize it into one query.
This is what I have so far:
SELECT centre, [Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday]
FROM (SELECT centre, [day], opening_time FROM centre_hours) AS p
PIVOT (MAX(opening_time) FOR [day] IN ([Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday])) AS pt
EDIT AGAIN
For those of you from the future wondering if/how I got around this, I ended up creating two separate pivot tables, then INSERTing the results of the first table, and UPDATEing with the results from the second.
Maybe this will help you. No update or insert. The same table as you original post