从SQL中的表(第一项)开始按周显示数据

时间:2018-07-10 08:56:41

标签: sql sql-server database

我有一个像这样的表:

我正在这样尝试(查询):

   --count of appointment ( day )   


 select DATENAME(WEEKDAY,AppDate) as Appointment,con.DrCode,doc.Doctor,con.AppDate,
  COUNT(con.AppDate)  as Appointment   from Consultation as con inner join DoctorMaster as doc on con.DrCode=doc.id where con.DrCode='2'
  GROUP BY CAST(AppDate AS DATE),con.DrCode,doc.Doctor,DATENAME(WEEKDAY,AppDate)


--count of appointment ( Week )


select con.DrCode,doc.Doctor,COUNT(con.AppDate) as Appointment from
Consultation as con inner join DoctorMaster as doc on con.DrCode=doc.id   where con.DrCode='2'
and (AppDate > DATEADD(year,-1,GETDATE()) and AppDate < GETDATE()-1)
group by DATEPART(wk,AppDate),con.DrCode,doc.Doctor

约会次数周明智显示,例如:

    Dr     Doctor     Appointment
    2    Kamal Goyal    3
    2    Kamal Goyal    17
    2    Kamal Goyal    14
    2    Kamal Goyal    8
    2    Kamal Goyal    10
    2    Kamal Goyal    1

但是我想明智地展示:

Day     Dr     Doctor     Appointment
sun     2    Kamal Goyal    3
mon     2    Kamal Goyal    Null
tues    2    Kamal Goyal    Null
wed     2    Kamal Goyal    8
thus    2    Kamal Goyal    Null
fri     2    Kamal Goyal    1
sat     2    Kamal Goyal    1

2 个答案:

答案 0 :(得分:0)

GROUP BY子句应描述结果集中所需的每一行-GROUP BY键的不同值定义了每一行。

因此,从AppDateSELECT中删除GROUP BY

select datename(weekday, AppDate) as Appointment, 
       con.DrCode, doc.Doctor,
       COUNT(con.AppDate) as Appointment
from Consultation con inner join
     DoctorMasterdoc
     on con.DrCode = doc.id
where con.DrCode = 2
group by datename(weekday, AppDate), con.DrCode, doc.Doctor;

这是您想要的吗?

答案 1 :(得分:0)

对日期范围(天)使用递归CTE,然后将结果与约会日期绑定。