2015-12-14 74 views
0

首先,對於可能無法正確表達問題標題表示歉意,我對SQL查詢不太瞭解。SQL從表列值中選擇子查詢IN

我有一個表「停車場」的列這樣的

| days_2  | from_hr | to_hr 
"1,2,3,4,5"  "08:00:00" "18:00:00" 
"0,1,2,3,4,5,6" "08:00:00" "22:00:00" 
... 
... 

我做了一個查詢這是工作確定:

SELECT Extract(dow from current_timestamp::DATE) as Day, 
    current_time BETWEEN from_hr and to_hr as ParkHour, 
    days_2, 
    from_hr, 
    to_hr 
FROM public.parkings; 

如果今天是星期一和當前時間是21:26 :00結果爲:

day | ParkHour | days_2  | from_hr | to_hr 
1 f   "1,2,3,4,5"  "08:00:00" "18:00:00" 
1 t   "0,1,2,3,4,5,6" "08:00:00" "22:00:00" 
... 
... 

我想修改這個查詢的方式,在第一列將被存儲res ULT(真/假),如果目前的日數爲表列DAYS_2該記錄,在這樣

SELECT Extract(dow from current_timestamp::DATE) in (1,2,3,4,5,6); 

的路要走,如果它現在是星期天其中(0)例如最終結果將是假的第一排,但在第二排是真的:

day | ParkHour | days_2  | from_hr | to_hr 
f f   "1,2,3,4,5"  "08:00:00" "18:00:00" 
t t   "0,1,2,3,4,5,6" "08:00:00" "22:00:00" 

我該如何做到這一點?

謝謝!

+1

如果你不熟悉關係數據庫中,DAYS_2欄應標準化,以包含一個單值 - 讓你的第一行會成爲五行。一旦你知道你在做什麼,你可以使用SQL99 ARRAY數據類型,並在你的查詢中使用UNNEST函數。 – cliffordheath

+0

你在用什麼數據庫? SQL Server。甲骨文......? – tale852150

+0

Postgresql。我提出了標籤問題 – sys49152

回答

1

嘗試

select 
    case 
    when Extract(dow from current_timestamp::DATE) = '0' then 't' else 'f' 
    when Extract(dow from current_timestamp::DATE) = '1' then 't' else 'f' 
    when Extract(dow from current_timestamp::DATE) = '2' then 't' else 'f' 
    when Extract(dow from current_timestamp::DATE) = '3' then 't' else 'f' 
    when Extract(dow from current_timestamp::DATE) = '4' then 't' else 'f' 
    when Extract(dow from current_timestamp::DATE) = '5' then 't' else 'f' 
    when Extract(dow from current_timestamp::DATE) = '6' then 't' else 'f' 
    end as day, 
    current_time BETWEEN from_hr and to_hr as ParkHour, 
    days_2, 
    from_hr, 
    to_hr 
from public.parkings; 

正如其他人所提到的,它會更容易,如果你的表結構是和/或如果使用數組更好。

HTH