iT邦幫忙

0

SQL查詢 開始日期和結束日期在同一個欄位的語法

各位大大好!
如題,
我現在拿到一個資料表,
格式如下圖
https://ithelp.ithome.com.tw/upload/images/20180313/20109044vM6DTJhyzm.png

我想讓使用者能在網站上分別輸入兩個日期並抓出資料
例如: 輸入2012和2019 能找到BBB這筆資料
輸入2013和2015 能找到BBB這筆資料
輸入2015和2016 能同時找到AAA和BBB這兩筆資料

請問有辦法在不把Year拆成兩個欄位的情況下做這樣的查詢嗎?

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2018-03-13 16:21:14 檢舉
為什麼會這樣設計欄位啊,根本是自找麻煩。
可以壓~善用left及right就可以了~
allenlwh iT邦高手 1 級 ‧ 2018-03-13 16:49:03 檢舉
真的不建議這樣設計欄位,會給自己造成困擾!
wei225890 iT邦新手 5 級 ‧ 2018-03-13 16:51:30 檢舉
感謝樓上各位,這是從客戶那邊拿到的,我頭也很痛
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
allenlwh
iT邦高手 1 級 ‧ 2018-03-13 16:40:06
最佳解答

輸入2012和2019 能找到BBB這筆資料

  where 2012>=year(convert(datetime,substring([Year],1,2)+'/01'+SUBSTRING([Year],3,5)))
  and 2019<=year(convert(datetime,SUBSTRING([Year],9,2)+'/01'+SUBSTRING([Year],11,5)))

輸入2013和2015 能找到BBB這筆資料

  where 2013>=year(convert(datetime,substring([Year],1,2)+'/01'+SUBSTRING([Year],3,5)))
  and 2015<=year(convert(datetime,SUBSTRING([Year],9,2)+'/01'+SUBSTRING([Year],11,5)))

輸入2015和2016 能同時找到AAA和BBB這兩筆資料

  where 2015>=year(convert(datetime,substring([Year],1,2)+'/01'+SUBSTRING([Year],3,5)))
  and 2016<=year(convert(datetime,SUBSTRING([Year],9,2)+'/01'+SUBSTRING([Year],11,5)))
allenlwh iT邦高手 1 級 ‧ 2018-03-13 16:44:12 檢舉

更簡潔的語法

  where 2012>=convert(int,SUBSTRING([Year],4,4))
  and 2019<=convert(int,SUBSTRING([Year],12,4))

  where 2013>=convert(int,SUBSTRING([Year],4,4))
  and 2015<=convert(int,SUBSTRING([Year],12,4))

  where 2015>=convert(int,SUBSTRING([Year],4,4))
  and 2016<=convert(int,SUBSTRING([Year],12,4))
wei225890 iT邦新手 5 級 ‧ 2018-03-13 16:52:00 檢舉

非常感謝您,我試試看!

抓後面年分 可以改用 RIGHT([Year],4) 也可以

我要發表回答

立即登入回答