多个Where条件或在同一个表上加入SQL Server

时间:2017-01-25 10:19:06

标签: sql sql-server

在SQL中,我需要基于两个datetime字段之间的每小时差异的结果集。例如,结果集必须像这样

我需要通过USERID,StartDate

进行Groupby

我对使用Sub Query或在同一个表之间加入感到困惑。所以,帮助我摆脱这个

+----------------------------------------------------------------+
| USERID    Date          6to7    7to8    8to9    9to10   10to11 |
+----------------------------------------------------------------+
| 119       2016-03-07    5                                      |
| 119       2016-03-10                     18                    |
| 5         2016-03-08    8                                      |
| 5         2016-03-10                             7             |
| 25        2016-03-09               2     20                    |
| 30        2016-03-11                     5                     |
+----------------------------------------------------------------+ 

表格如下所示

  ID    UserId         StartDate            EndDate
7494    119    2016-03-07 06:35:55.000      2016-03-07 06:40:55.000
7495    5      2016-03-08 06:02:33.000      2016-03-08 06:10:33.000
7496    25     2016-03-09 07:58:33.000      2016-03-09 08:20:33.000
7497    25     2016-03-09 07:54:20.000      2016-03-09 07:56:20.000
7498    119    2016-03-10 08:35:55.000      2016-03-10 08:53:55.000
7499    5      2016-03-10 09:02:33.000      2016-03-10 09:09:33.000
7500    30     2016-03-11 08:58:33.000      2016-03-11 08:59:33.000
7501    30     2016-03-11 08:54:20.000      2016-03-11 08:58:20.000

这是我试过的代码

SELECT  UserID, 
        StartDate,
        (SUM(DATEDIFF(SECOND, CAST(SWITCHOFFSET(TODATETIMEOFFSET(StartDate,      '-00:00'), '+06:00') AS DATETIME),
CAST(SWITCHOFFSET(TODATETIMEOFFSET(EndDate, '-00:00'), '+06:00') AS    DATETIME))
))'HRS6TO7' 
FROM TMCallResultLog 
WHERE  CAST(StartDate AS TIME) BETWEEN '06:00:00' AND '07:00:00' AND
EndDate IS NOT NULL AND 
StartDate IS NOT NULL 
GROUP BY UserID, StartDate

1 个答案:

答案 0 :(得分:1)

这称为条件聚合。此外,您需要在分组之前将StartDate强制转换为date(以切断时间):

select
  UserID,
  CAST(StartDate as DATE) StartDate,
  SUM(
    CASE
      WHEN CAST(StartDate AS TIME) BETWEEN '06:00:00' AND '07:00:00' AND
      THEN DATEDIFF(...)
      ELSE 0
    END
   ) as [6to7],
  SUM(
    CASE
      WHEN CAST(StartDate AS TIME) BETWEEN '07:00:00' AND '08:00:00' AND
      THEN DATEDIFF(...)
      ELSE 0
    END
   ) as [7to8],
   ...
from ...
where EndDate IS NOT NULL AND StartDate IS NOT NULL 
group by
  UserID,
  CAST(StartDate as DATE)