使用datetime MSSQL Query创建统计表

时间:2012-10-30 14:33:31

标签: sql-server

我有一张桌子让我很难过:

Person    datetime1                   datetime2
Eric      2012-10-01 09:00:05.000     2012-10-01 22:00:00.000
Anna      2012-10-02 06:00:05.000     2012-10-03 12:00:05.000
Richard   2012-10-03 09:00:05.000     2012-10-04 02:00:05.000
Chuck     2012-10-01 12:00:05.000     2012-10-01 23:00:05.000

我正在尝试编写一个查询,它为我提供了统计信息表。此表包含有关用户何时登录和注销的信息(每日粒度):

Date        logged_in  logged_off
2012-10-01  2          2
2012-10-02  1          0
2012-10-03  1          1
2012-10-04  0          1

根据我的研究,枢轴命令可以解决问题吗?

select Person,
SUM(case when datetime1 = '2012-10-01' then 1 else 0 end) as [loggeed_in],
SUM(case when datetime2 = '2012-10-01'  then 1 else 0 end) as [logged_of]
from table
group by Person

这不起作用......你有什么想法吗?

2 个答案:

答案 0 :(得分:1)

这将修复当前查询,但不知道它是否能解决整个问题......

select Person,
SUM(case when convert(varchar(10), datetime1, 111) = '2012/10/01' then 1 else 0 end) as [loggeed_in],
SUM(case when convert(varchar(10), datetime2, 111) =  '2012/10/01'  then 1 else 0 end) as [logged_of]
from table
group by Person
编辑:我相信这会更符合要求......

SELECT 
    [Date] = dt,
    logged_in = (
        SELECT COUNT(*)
        FROM table1
        WHERE convert(varchar(10), datetime1, 111) = convert(varchar(10), dt, 111)),
    logged_off = (
        SELECT COUNT(*)
        FROM table1
        WHERE convert(varchar(10), datetime2, 111) = convert(varchar(10), dt, 111))
FROM (
    SELECT TOP 1000
        row_number() OVER(ORDER BY (SELECT 0)) AS N
        FROM master.dbo.syscolumns sc1, master.dbo.syscolumns sc2) tally
    CROSS APPLY(
        SELECT dt = DATEADD(dd, tally.N - 1, '2012-10-1')) tallydt
WHERE dt BETWEEN (SELECT MIN(dateadd(dd, -1, datetime1)) FROM table1) AND (SELECT MAX(datetime2) FROM table1)
GROUP BY dt 
ORDER BY dt

答案 1 :(得分:0)

以下是工作解决方案:

WITH O AS (
SELECT
CAST([login Date & Time] AS DATE) loginDate
,COUNT(*) logined
 FROM table
 GROUP BY CAST([login Date & Time] AS DATE)
 ), C AS (
SELECT 
CAST([Close Date & Time] AS DATE) CloseDate
,COUNT(*) Closed
 FROM table
WHERE [Close Date & Time] IS NOT NULL
GROUP BY CAST([Close Date & Time] AS DATE)
 )
 SELECT
COALESCE(C.CloseDate, O.loginDate) TheDate
--,O.loginDate
--,C.CloseDate
,O.logined
,C.Closed
  FROM O 
  FULL JOIN C
 ON O.loginDate = C.CloseDate
 ORDER BY TheDate