mssql值班日期统计

使用sql语句对值班日期统计练习

代码
--author:【DBA】小七
--
createtime:2009-11-27

set nocount on
declare @t table (name char(10) ,Date datetime,isduty char(1))
INSERT INTO @t
select '李四',convert(datetime,'2009-10-5',120),'1' UNION ALL
SELECT '张三',convert(datetime,'2009-10-12',120),'1' union all
SELECT '张三',convert(datetime,'2009-10-13',120),'1' union all
select '李四',convert(datetime,'2009-10-14',120),'1' UNION ALL
select '张三',convert(datetime,'2009-10-15',120),'1' UNION ALL
select '李四',convert(datetime,'2009-10-16',120),'1' UNION ALL
select '李四',convert(datetime,'2009-10-17',120),'1' UNION ALL
select '张三',convert(datetime,'2009-10-18',120),'1' UNION ALL
select '王五',convert(datetime,'2009-10-19',120),'1' UNION ALL
select '李四',convert(datetime,'2009-10-19',120),'1' UNION ALL
select '张三',convert(datetime,'2009-10-19',120),'1' UNION ALL
SELECT '张三',convert(datetime,'2009-10-20',120),'1' union all
select '李四',convert(datetime,'2009-10-25',120),'1' UNION ALL
select '李四',convert(datetime,'2009-10-28',120),'1' UNION ALL
select '李四',convert(datetime,'2009-11-2',120),'1'

SELECT * FROM @t
select name,sum(星期一) '星期一',sum(星期二) '星期二',sum(星期三) '星期三',sum(星期四) '星期四',sum(星期五) '星期五',sum(星期六) '星期六',sum(星期日) '星期日' from
(
select name,
isnull((case when datename(weekday,date)='星期一' then count(isduty) end),0) '星期一',
isnull((case when datename(weekday,date)='星期二' then count(isduty) end),0) '星期二',
isnull((case when datename(weekday,date)='星期三' then count(isduty) end),0) '星期三',
isnull((case when datename(weekday,date)='星期四' then count(isduty) end),0) '星期四',
isnull((case when datename(weekday,date)='星期五' then count(isduty) end),0) '星期五',
isnull((case when datename(weekday,date)='星期六' then count(isduty) end),0) '星期六',
isnull((case when datename(weekday,date)='星期日' then count(isduty) end),0) '星期日'
from @t where date between '2009-10-12' and '2009-10-28' group by name,datename(weekday,date) ) as b
group by name


name Date isduty
---------- ------------------------------------------------------ ------
李四 2009-10-05 00:00:00.000 1
张三
2009-10-12 00:00:00.000 1
张三
2009-10-13 00:00:00.000 1
李四
2009-10-14 00:00:00.000 1
张三
2009-10-15 00:00:00.000 1
李四
2009-10-16 00:00:00.000 1
李四
2009-10-17 00:00:00.000 1
张三
2009-10-18 00:00:00.000 1
王五
2009-10-19 00:00:00.000 1
李四
2009-10-19 00:00:00.000 1
张三
2009-10-19 00:00:00.000 1
张三
2009-10-20 00:00:00.000 1
李四
2009-10-25 00:00:00.000 1
李四
2009-10-28 00:00:00.000 1
李四
2009-11-02 00:00:00.000 1

name 星期一 星期二 星期三 星期四 星期五 星期六 星期日
---------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
李四 1 0 2 0 1 1 1
王五
1 0 0 0 0 0 0
张三
2 2 0 1 0 0 1



原文地址:https://www.cnblogs.com/dba_xiaoqi/p/1852556.html