2010-07-04 66 views
0

我有一個表格式(類似於你在大學有課程表):這可以寫成查詢而不是使用函數嗎?

create table match_times 
(
    match_time  varchar2(20 char), 
    match_sun_day char(1 char), 
    match_mon_day char(1 char), 
    match_tue_day char(1 char), 
    match_wed_day char(1 char), 
    match_thu_day char(1 char), 
    match_fri_day char(1 char), 
    match_sat_day char(1 char) 
) 
comment on column match_times.match_time is 'E.g. ''08:00-08:50'''; 
comment on column match_times.match_sun_day is '''U'' or null'; 
comment on column match_times.match_mon_day is '''M'' or null'; 
comment on column match_times.match_tue_day is '''T'' or null'; 
comment on column match_times.match_wed_day is '''W'' or null'; 
comment on column match_times.match_thu_day is '''R'' or null'; 
comment on column match_times.match_fri_day is '''F'' or null'; 
comment on column match_times.match_sat_day is '''S'' or null'; 

我想編寫一個查詢,將讓我如:

8:00 - 9:00 MTF 
9:00 - 10:15 TR 

這可以可以使用函數輕鬆完成,但我很好奇這是否可以通過使用SQL查詢完成。這不重要,它只是爲了知識:)

編輯:對不起,我錯過了一個重要的澄清。每個比賽時間可以有多行。它可以在一行上有MF,在下一行上有W。現在我明白你們爲什麼要求實際的創建表語句。

+3

你能否包含實際的create table語句?這樣可以更好地瞭解表格的外觀。我無法從這種格式中確切地知道發生了什麼。 – 2010-07-04 12:38:25

+3

你能發佈更多關於表格的信息嗎?例如,數據類型?星期幾布爾值是什麼?是時間VARCHAR? – xil3 2010-07-04 12:40:05

+0

對不起,我現在發佈了實際的create table語句。我認爲使用樣本數據而不是數據類型會更具可讀性。 – Zesty 2010-07-04 13:43:16

回答

2

這應該工作:

with days AS (
    select 
    match_time, 
    max(coalesce(match_sun_day, '')) sun, 
    max(coalesce(match_mon_day, '')) mon, 
    max(coalesce(match_tue_day, '')) tue, 
    max(coalesce(match_wed_day, '')) wed, 
    max(coalesce(match_thu_day, '')) thu, 
    max(coalesce(match_fri_day, '')) fri, 
    max(coalesce(match_sat_day, '')) sat 
    from 
    match_times 
    group by 
    match_time 
) 
    select 
    match_time + ' ' + sun+mon+tue+wed+thu+fri+sat 
    from 
    days 

我沒有一個安裝方便測試它。最糟糕的情況是,如果你的數據庫在max的非空字符串之前沒有訂購空字符串,請用'a'替換'',然後在字符串建立的每一天放入一個案例。

+0

幹得好!令人印象深刻的是,你在精神上做到了。小字體錯誤 - 用||替換+。感謝回覆。 – Zesty 2010-07-04 14:39:45

0

是的,你可以。但這是一個可怕的模式,使得諸如「向我展示教授在這個學期教授的總小時數」這樣的疑問非常困難。

+0

你是對的。不幸的是,我無法控制這張桌子。 – Zesty 2010-07-04 13:44:11

2

假設你只有每個獨特的時間跨度一行(沒有主鍵列):

SELECT 
    match_time, 
    COALESCE(match_sun_time, '') + 
    COALESCE(match_mon_time, '') + 
    COALESCE(match_tue_time, '') + 
    COALESCE(match_wed_time, '') + 
    COALESCE(match_thu_time, '') + 
    COALESCE(match_fri_time, '') + 
    COALESCE(match_sat_time, '') 
FROM 
    Match_Times 
+0

我的不好。每個比賽時間可以有多行。對不起,我忘了提這個。否則,您的查詢是正確的。 – Zesty 2010-07-04 14:13:56

相關問題