我写了这个查询它工作正常但是当我向它添加group by Date
时,它会返回一个错误:
子查询返回超过1等
我的代码:
Declare @FromDate datetime set @FromDate='2014-11-01 09:01:11.927'
Declare @ToDate datetime set @ToDate='2014-11-06 05:01:11.927'
Declare @Day int
Set @Day= (Select Count(*) from Attendance where
AttendanceDate >= @FromDate AND AttendanceDate < dateadd(day,1, @ToDate )
AND Attendance.DepartmentShiftHistory_ID=47
and organization_id=40
group by Attendance.DepartmentShiftHistory_ID,cast(AttendanceDate as date),User_ID
)
print @Day
答案 0 :(得分:0)
当您执行原始查询(没有分组)时,它会返回一个类似1337的数字。 按日期对其进行分组时,它将返回与原始数字(1000,300,30,7)相加的数字,并且您无法为变量分配该数字。
如果您希望获得总天数,请按部分离开。
如果您希望获得每天的结果,则应将其插入临时表(如
)Select AttendanceDate, Count(*)
from Attendance
into #Days
where AttendanceDate >= @FromDate AND AttendanceDate < dateadd(day,1, @ToDate )
AND Attendance.DepartmentShiftHistory_ID=47
and organization_id=40
group by Attendance.DepartmentShiftHistory_ID,cast(AttendanceDate as date),User_ID
SELECT * FROM #Days
答案 1 :(得分:0)
试试这个
Declare @FromDate datetime set @FromDate='2014-11-01 09:01:11.927'
Declare @ToDate datetime set @ToDate='2014-11-06 05:01:11.927'
Declare @Day int
Set @Day= (Select top 1 Count(*) OVER () from Attendance where
AttendanceDate >= @FromDate AND AttendanceDate < dateadd(day,1, @ToDate )
AND Attendance.DepartmentShiftHistory_ID=47
and organization_id=40
group by Attendance.DepartmentShiftHistory_ID,cast(AttendanceDate as date),User_ID
)
print @Day
此处我另外使用 - top 1 Count(*)OVER(),即用于获取“按语句分组返回的记录数”
答案 2 :(得分:0)
感谢回复,但没有一个解决方案适合我,所以我尝试了这个并且工作
set @Day=(select count(*) from (Select count(*) 'is' from Attendance where
AttendanceDate >= @FromDate AND AttendanceDate < dateadd(day,1, @ToDate )
AND Attendance.DepartmentShiftHistory_ID=@DepartmentShiftHistory_ID
and organization_id=@OrgID
group by Attendance.DepartmentShiftHistory_ID,cast(AttendanceDate as date)
) as c)