当前位置: 代码迷 >> Sql Server >> 一个月内每日的人数统计
  详细解决方案

一个月内每日的人数统计

热度:86   发布时间:2016-04-24 10:00:43.0
一个月内每天的人数统计
求sql语句如何进行统计
问题如图片所示:

------解决思路----------------------

WITH test AS (
SELECT '201401' AS MON,'aa' AS VAL
UNION ALL
SELECT '201401','bb'
UNION ALL
SELECT '201401','aa'
UNION ALL
SELECT '201402','cc'
UNION ALL
SELECT '201402','bb'
UNION ALL
SELECT '201403','aa'
UNION ALL
SELECT '201403','cc'
UNION ALL
SELECT '201404','bb'
UNION ALL
SELECT '201404','ss'
)
SELECT * INTO test2 FROM test AS t



SELECT '*' AS p, tt.mon, COUNT(DISTINCT tt.val) AS Totalcount,SUM(tt.NewFlag) AS TotalCount1,tt.total+SUM(tt.NewFlag) AS TotalCount2
FROM (
     SELECT DISTINCT t.mon,t.val, CASE WHEN t2.val IS NULL THEN 1 ELSE 0 END AS NewFlag,t3.total
      FROM test2 AS t 
     LEFT JOIN (SELECT DISTINCT mon,val FROM test2 ) AS t2 ON t2.mon<t.mon AND t2.val=t.val
     CROSS APPLY (SELECT DISTINCT count(distinct val) AS total FROM test2 WHERE mon<t.mon ) AS t3  
     
     ) tt 
GROUP BY tt.mon,tt.total

------解决思路----------------------

WITH test AS (
SELECT '201401' AS mon,'aa' AS val
UNION ALL
SELECT '201401','bb'
UNION ALL
SELECT '201401','aa'
UNION ALL
SELECT '201402','cc'
UNION ALL
SELECT '201402','bb'
UNION ALL
SELECT '201403','aa'
UNION ALL
SELECT '201403','cc'
UNION ALL
SELECT '201404','bb'
UNION ALL
SELECT '201404','ss'
),
t as 
(select t1.mon,COUNT(distinct t1.val)
 as totalcount,
 COUNT(distinct t2.val)as totalcount2 from test as t1 join test as t2 
 on t1.mon>=t2.mon
 group by t1.mon) 
 select mon,totalcount,
 case  when mon=(select MIN(mon) from t) then totalcount
 else (select a.totalcount2-b.totalcount2 from t as a join t as b
 on a.mon=b.mon+1 and a.mon=t.mon) end as 
 totalcount1 ,totalcount2 from t
  相关解决方案