试图找到工作日,周末以及工作日+周末记录的不同客户的总数

时间:2012-02-01 02:44:42

标签: sql sql-server

我的表格结构如下:

node_id | client_id | timestamp
--------+-----------+-----------
    1   |    102    | 2012-02-01 (weekday)
--------+-----------+-----------
    2   |    104    | 2012-02-01 (weekday)
--------+-----------+-----------
    2   |    106    | 2012-02-02 (weekday)
--------+-----------+-----------
    1   |    106    | 2012-02-02 (weekend)
--------+-----------+-----------

(added fake weekday/weekend to simplify things)

我需要找到登录的不同客户端ID的总数:

  • 工作日
  • 周末
  • 工作日和周末

是否可以在MSSQL中执行此操作?或者我是否必须简单地转储所有数据并在程序中解析它?

修改

从上表中,所需的输出会告诉我:

3 people were logged on Mon-Fri by nodes 1 & 2
1 person was logged on Sat-Sun by nodes 1
1 person was logged on Mon-Sun by nodes 1 & 2

基本上,我需要知道有多少客户端登录的是Mon-Fri,Sat-Sun,Mon-Sun以及哪些节点。

3 个答案:

答案 0 :(得分:0)

您可以使用datepart(工作日,?)查找日期的星期几(请参阅http://msdn.microsoft.com/en-us/library/ms174420.aspx);那么只需指定你有兴趣将哪些人分组在一起。

答案 1 :(得分:0)

如果我理解正确,你可以试试这个

SET DATEFIRST 1
declare @tbl table (node_id int identity(1,1), client_id int, dtm datetime)

insert into @tbl (client_id,dtm) values (1,'20111001'), (1,'20111001'),(1,'20111002'),(1,'20111003'),(1,'20111004')
,(2,'20111001'), (2,'20111003'),(2,'20111003'),(2,'20111003'),(2,'20111004')
--weekday
select client_id, COUNT(*)
FROM @tbl
WHERE DATEPART(DW,dtm)<6
GROUP BY client_id
--weekend
select client_id, COUNT(*)
FROM @tbl
WHERE DATEPART(DW,dtm)>5
GROUP BY client_id

此解决方案使用DATEPART功能。 要设置一周的第一天,请使用SET DATEFIRST

<强> EDITED 在SQL-Server 2005+中,您可以这样做:

SET DATEFIRST 1
DECLARE @tbl table (node_id int, client_id int, dtm datetime)

INSERT INTO @tbl (node_id,client_id,dtm) VALUES (1,102,'20120201'),(2,104,'20120201'),(2,106,'20120202'),(1,106,'20120204')

--weekday
SELECT CAST(COUNT(*) as varchar)+' people were logged on Mon-Fri by nodes '+
    (select cast(node_id as varchar)+',' as 'data()' from @tbl WHERE DATEPART(DW,dtm)<6 GROUP BY node_id for xml path(''))
FROM @tbl
WHERE DATEPART(DW,dtm)<6

--weekend
SELECT CAST(COUNT(*) as varchar)+' people were logged on Sat-Sun by nodes '+
    (select cast(node_id as varchar)+',' as 'data()' from @tbl WHERE DATEPART(DW,dtm)>5 GROUP BY node_id for xml path(''))
FROM @tbl
WHERE DATEPART(DW,dtm)>5

--all week
SELECT CAST(COUNT(*) as varchar)+' people were logged on Mon-Sun by nodes '+
    (select cast(node_id as varchar)+',' as 'data()' from @tbl GROUP BY node_id for xml path(''))
FROM @tbl

答案 2 :(得分:0)

WITH myCTE AS (
SELECT node_id, clientid, datepart(weekday, timestamp) wkday
FROM YourTable
)
SELECT T1.node_id, T1.count(distinct clientid) total, 'weekdays' category
FROM myCTE T1
WHERE wkday in (2,3,4,5,6) --weekdays
UNION ALL
SELECT T1.node_id, T1.count(distinct clientid) total, 'weekends' category
FROM myCTE T1
WHERE wkday in (1,7) --weekends
SELECT T1.node_id, T1.count(distinct clientid) total, 'mon-sat' category
FROM myCTE T1
WHERE wkday in (2,3,4,5,6,7) --mon-sat

希望这有助于...使用上面的脚本,如果您需要更多不同天组合的分组,可以按照这样做,只需继续添加union all并更改where子句标准。