sql语句:按日期范围计算

时间:2018-01-02 00:47:23

标签: sql date count range

说我有下表

license_num(varchar)-------- checkout_datetime(datetime)

ABC-123 -------------------------------------------- 2017-12-29 00:07:00

ABC-123 ------------------------------------------- 2017 -12-30 00:10:00

XYZ-456 ------------------------------------------- 2017 -12-30 00:10:00

XYZ-456 ------------------------------------------- 2017 -12-31 00:11:00

我需要一个产生以下结果的SQL语句:

LicenseNumber -------- 12/29 12/30 --- --- --- 12/31 TotalOfWeek

ABC-123 ----------------------------------- 1 -------- ----- ------------- 1 0 2 ------------------

XYZ-456 ----------------------------------- 0 -------- ------ 1 ------------ 1 ------------------ 2

如何编写此类SQL语句?

感谢帮助!

1 个答案:

答案 0 :(得分:0)

试试这个.. :)我做对了......

   SELECT *,CONVERT(Varchar(10),
  (DATEPART(MM,checkout_datetime)))+'/'+CONVERT(Varchar(10),
  (DATEPART(DD,checkout_datetime)))  AS NewColName,1 AS Count
  INTO #TempPivotTab2
  FROM TransTable

  SELECT *
  FROM
   (
   SELECT license_num,NewColName,Count
   FROM   #TempPivotTab2 
   ) AS SourceTable
   PIVOT
   (
   SUM(Count)
   FOR NewColName IN ([12/29],[12/30],[12/31])
   )Piv