我有一张桌子,有一些有日期的用户...
| Employee_Name | Date |
| CG | 2019-04-22 |
| CG | 2019-04-26 |
| CG | 2019-04-24 |
我正在尝试获取结果,因此当我查询并说Date BETWEEN (@start AND @end)
时,它会给我类似以下结果:
EMPLOYEE_NAME | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday |
CG | 2019-04-22 | NULL | 2019-04-24 | NULL | 2019-04-26 | NULL | NULL |
我实在不知所措地挠着头-我知道我可以用枢轴做到这一点。
答案 0 :(得分:2)
以下内容应该可以工作(如果@ d2-@ d1 <7,则完全正确,否则它将显示每个工作日的第一个日期):
SELECT Employee_Name
, MIN(CASE WHEN DATENAME(dw, Date) = 'Sunday' THEN Date END) AS Sunday
, MIN(CASE WHEN DATENAME(dw, Date) = 'Monday' THEN Date END) AS Monday
, MIN(CASE WHEN DATENAME(dw, Date) = 'Tuesday' THEN Date END) AS Tuesday
, MIN(CASE WHEN DATENAME(dw, Date) = 'Wednesday' THEN Date END) AS Wednesday
, MIN(CASE WHEN DATENAME(dw, Date) = 'Thursday' THEN Date END) AS Thursday
, MIN(CASE WHEN DATENAME(dw, Date) = 'Friday' THEN Date END) AS Friday
, MIN(CASE WHEN DATENAME(dw, Date) = 'Saturday' THEN Date END) AS Saturday
FROM t
WHERE Date BETWEEN @d1 AND @d2
GROUP BY Employee_Name
答案 1 :(得分:0)
这里是Pivot解决方案。
我添加了更多示例数据(一名员工和两名约会对象)进行测试:
declare @weekday table (weekday varchar(10))
insert into @weekday (weekday) values
('Monday'),
('Tuesday'),
('Wednesday'),
('Thursday'),
('Friday'),
('Saturday'),
('Sunday')
select p.employee_name,[Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday],[Sunday]
from (
select t.employee_name,t.date,w.weekday from (
select *, datename(weekday,date) as weekday
from #test) t
right join @weekday w
on w.weekday = t.weekday) s
pivot
(max(date)
for weekday in ([Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday],[Sunday])
) as p
where p.employee_name is not null
请相应地更改表格名称。 (我使用了#test)
测试结果: