0

我正在跟踪 Microsoft SQL Server 2008 R2 中的客户商店条目数据,如下所示:

DoorID        DateTimeStamp               EntryType
1             2013-09-02 09:01:16.000     IN
1             2013-09-02 09:04:09.000     IN
1             2013-09-02 10:19:29.000     IN
1             2013-09-02 10:19:30.000     IN
1             2013-09-02 10:19:32.000     OUT
1             2013-09-02 10:26:36.000     IN
1             2013-09-02 10:26:40.000     OUT

我不想计算OUT行数,只是IN

我相信它需要按 和 分组DateDoorID然后得到总小时数。

我希望它像这样出来。

Date        DoorID  HourOfDay TotalInPersons
2013-09-02  1       0         0
2013-09-02  1       1         0
2013-09-02  1       2         0
2013-09-02  1       3         0
2013-09-02  1       4         0
2013-09-02  1       5         0
2013-09-02  1       6         0
2013-09-02  1       7         0
2013-09-02  1       8         0
2013-09-02  1       9         2
2013-09-02  1       10        3
2013-09-02  1       11        0
2013-09-02  1       12        0
2013-09-02  1       13        0
2013-09-02  1       14        0
2013-09-02  1       15        0
2013-09-02  1       16        0
2013-09-02  1       17        0
2013-09-02  1       18        0
2013-09-02  1       19        0
2013-09-02  1       20        0
2013-09-02  1       21        0
2013-09-02  1       22        0
2013-09-02  1       23        0
4

3 回答 3

3
SELECT 
  [Date] = CONVERT(DATE, DateTimeStamp), 
  DoorID,
  HourOfDay = DATEPART(HOUR, DateTimeStamp),
  TotalInPersons = COUNT(*)
FROM dbo.tablename
WHERE EntryType = 'IN'
GROUP BY 
  CONVERT(DATE, DateTimeStamp),
  DoorID,
  DATEPART(HOUR, DateTimeStamp)
ORDER BY
  [Date], DoorID, HourOfDay;

当然,如果您需要所有时间,即使没有表示任何行,这是一种解决方案(它将任何一天的输出限制为当天至少有一个IN入口的门):

;WITH h AS 
(
  SELECT TOP (24) h = number FROM Master..spt_values 
  WHERE type = N'P' ORDER BY number
),
doors AS
(
  SELECT DISTINCT DoorID, [Date] = CONVERT(DATE,DateTimeStamp) 
  FROM dbo.tablename WHERE EntryType = 'IN'
)
SELECT 
  d.[Date],
  d.DoorID,
  HourOfDay = h.h,
  TotalInPersons = COUNT(t.EntryType) 
FROM doors AS d CROSS JOIN h
LEFT OUTER JOIN dbo.tablename AS t
ON CONVERT(DATE, t.DateTimeStamp) = d.[Date]
AND t.DoorID = d.DoorID
AND DATEPART(HOUR, t.DateTimeStamp) = h.h
AND t.EntryType = 'IN'
GROUP BY d.[Date], d.DoorID, h.h
ORDER BY d.[Date], d.DoorID, h.h;
于 2013-09-04T16:06:56.263 回答
1

像这样的东西怎么样:

SELECT 
  CAST(DateTimeStamp AS DATE) AS Date
  ,DoorID        
  ,DATEPART(HOUR, DateTimeStamp) AS HourOfDay
  ,COUNT(*) AS TotalInPersons
FROM StoreTable
WHERE EntryType = 'IN'
GROUP BY
  CAST(DateTimeStamp AS DATE)
  ,DoorID        
  ,DATEPART(HOUR, DateTimeStamp)
于 2013-09-04T16:13:47.360 回答
0

这应该有效。我猜你会如何拉 DoorID 和 TotalPersons,但整体逻辑是正确的

SELECT CONVERT(date,dateColumn) AS Date, 
  datepart(hh,dateColumn) AS HourOfDay, 
  DoorID,
  COUNT(people) AS TotalPersons
FROM yourtable
WHERE EntryType = 'IN'
GROUP BY CONVERT(date,dateColumn), datepart(hh,dateColumn), DoorID
ORDER BY CONVERT(date,dateColumn), datepart(hh,dateColumn)
于 2013-09-04T16:06:57.123 回答