iT邦幫忙

0

SQL 查詢每個月營業日的最後一天

sql

https://ithelp.ithome.com.tw/upload/images/20190118/2011393278N4CRXYS6.jpghttps://ithelp.ithome.com.tw/upload/images/20190118/20113932o7Ekg29981.jpg

表格如圖
欄位內容是所有營業日
請問如何SELECT出 每個月的最後一個營業日??

slime iT邦大師 1 級 ‧ 2019-01-18 15:41:26 檢舉
select
substring(convert(char(10),CTL_DATE,111),1,7),max(CTL_DATE)

group by substring(convert(char(10),CTL_DATE,111),1,7)
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
暐翰
iT邦大師 1 級 ‧ 2019-01-18 15:39:11
最佳解答

看圖片我猜測你是使用SSMS > DB是SQL Server
在SQL Server可以使用SQL方言,Group by DATEPART() + max(CTL_Date) 方式,取得每個月的最後一個營業日

select DATEPART(Year, [CTL_Date]) year
	,DATEPART(MONTH, [CTL_Date])  month
	, max([CTL_Date])  Last_CTL_Date
from T
group by DATEPART(Year, [CTL_Date]),DATEPART(MONTH, [CTL_Date])

或是 純真的人大大 的補充:

select Year([CTL_Date]) year
	,MONTH([CTL_Date])  month
	, max([CTL_Date])  Last_CTL_Date
from T
group by Year([CTL_Date]),MONTH([CTL_Date])

結果

year        month       Last_CTL_Date
----------- ----------- -----------------------
2018        1           2018-01-25 00:00:00.000
2018        2           2018-02-27 00:00:00.000

Test Table:

CREATE TABLE T
	([CTL_Date] datetime)
;
	
INSERT INTO T
	([CTL_Date])
VALUES
	('2018-01-20 00:00:00'),
	('2018-01-25 00:00:00'),
	('2018-02-07 00:00:00'),
	('2018-02-27 00:00:00')
;
Zed_Yang iT邦新手 3 級 ‧ 2019-01-18 15:44:55 檢舉

謝謝 原來是使用DatePART去個別取出年跟月
再做群組分類

直接用year()或month()也是可以..

暐翰 iT邦大師 1 級 ‧ 2019-01-18 16:24:24 檢舉

純真的人大大,謝謝補充/images/emoticon/emoticon12.gif
我更新回答了

我要發表回答

立即登入回答