一、group by分組函數大家很熟悉,就是按照某一列進行分組排序。但是很多時候分組排序的時候,我們需要按照日或者月或者年來分組當前的數據。但是數據表中時間的字段是精確到分鍾的,這種要怎么處理呢?
1. 其實很簡單,只要找到當前表中的日期列,並且其轉換成需要排序的年月格式便可,並且取出對應的字符長度。
2. 如下,我需要將金額數據按照月度匯總,那么我需要做的就是把當前日期先轉換成年月格式的日期,然后按照分組。
3. 需要注意的是,需要將group后的日期字段和查詢列的字段都轉換為年月格式的字符。如 2019-05 。
select sum(c.fOCryAmtWiTax) 本月接單金額,CONVERT(varchar(7),a.fappdate,120) 月份 From t_COPD_OrdMst a with(nolock) Left Join t_CRMM_CstMst b with(nolock) on a.fCCode = b.fCCode --fZoneCode N代表內貿 Y代表外貿 Left Join t_COPD_OrdItem c with(nolock) on a.fOrdNo = c.fOrdNo --fOCryAmtWiTax 折后含稅金額,替換a.fordallamt+a.fselallamt left Join t_BOMM_GoodsMst d with(nolock) on c.fGoodsID = d.fGoodsID Left Join t_CRMM_Zone e with(nolock) on B.fZoneCode=e.fZoneCode Left Join t_COPM_GoodsSortMst f with(nolock) on d.fSortCode=f.fSortCode left join t_CRMM_CrmSortMst g on g.fCustSortCode=b.fCustSortCode where a.fappdate>'2018-12-31' group by CONVERT(varchar(7),a.fappdate,120) order by CONVERT(varchar(7),a.fappdate,120)
4. 常用的日期格式有以下:
select CONVERT(varchar(12) , getdate(), 101 ) 05/19/2019 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 102 ) 2019.05.19 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 103 ) 19/05/2019 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 104 ) 19.05.2019 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 105 ) 19-05-2019 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 106 ) 19 05 2019 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 107 ) 05 19, 2019 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 108 ) 09:15:33 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 109 ) 05 19 2019 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 110 ) 05-19-2019 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 111 ) 2019/05/19 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 112 ) 20190519 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 113 ) 19 05 2019 0 --------------------------------------------- select CONVERT(varchar(12) , getdate(), 114 ) 09:16:06:747 ---------------------------------------------
5. 如果需要去日期中相關的值,有以下方法
YEAR('2018-05-17 00:00:00') --年 MONTH('2018-05-15 00:00:00') --月 DAY('2008-05-15 00:00:00') --日 DATEPART ( datepart , date ) DATEPART(MM,'2018-05-15 00:00:00') 年份 yy、yyyy 季度 qq、q 月份 mm、m 每年的某一日 dy、y 日期 dd、d 星期 wk、ww 工作日 dw 小時 hh 分鍾 mi、n 秒 ss、s 毫秒 ms
謝謝觀看!!!