0

我有一张小桌子,这让我很难过:

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

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

4

2 回答 2

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
于 2012-10-30T14:49:54.493 回答
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
于 2012-10-31T09:26:21.697 回答