我的SQL查询中出现以下错误。有人可以帮忙:
Msg 1060,Level 15,State 1,Line 50 为TOP或FETCH子句行计数参数提供的行数必须是整数。
with
-- sample data
Tbl_PCode as (
select *
from (values
(450001,cast('8/1/2016' as date), 'REG', 40.50, 1),
(450001,cast('8/1/2016' as date), 'OT', 10.50, 2),
(450002,cast('8/2/2016' as date), 'REG', 29.50, 3),
(450003,cast('8/3/2016' as date), 'REG', 32.50, 4),
(450003,cast('8/3/2016' as date), 'VACC', 8.50, 5),
(450004,cast('8/3/2016' as date), 'VACC', 8.50, 6),
(450005,cast('8/3/2016' as date), 'VACC', 35.50,7)
) t(ID,Date,PCode,Hours,pos)
),
Tbl_TCode as (
select *
from (values
(450001,cast('8/1/2016' as date), 'SHOPC', 10.50, 1),
(450001,cast('8/1/2016' as date), 'FIELDC', 30.50, 2),
(450001,cast('8/1/2016' as date), 'SHOPC', 2.00, 3),
(450001,cast('8/1/2016' as date), 'FIELDC', 8.00, 4),
(450002,cast('8/2/2016' as date), 'SHOPC', 2.00, 5),
(450002,cast('8/2/2016' as date), 'FIELDC', 27.50, 6),
(450003,cast('8/3/2016' as date), 'SHOPC', 20.50, 7),
(450003,cast('8/3/2016' as date), 'FIELDC', 12.50, 8),
(450003,cast('8/3/2016' as date), 'SHOPC', 8.00, 9),
(450003,cast('8/3/2016' as date), 'FIELDC', 0.00, 10),
(450004,cast('8/3/2016' as date), 'SHOPC', 8.50, 11),
(450005,cast('8/3/2016' as date), 'SHOPC', 35.50, 12)
) t(ID,Date,TCode,Hours,pos)
),
tally as (
select top(500000) rn= row_number() over(order by (select null))
from sys.all_objects
),
-- query
t_P as (
select *, rn=row_number() over(partition by ID,Date order by pos)
from Tbl_PCode
cross apply (select top(Hours) 1 n
from tally
) x
),
t_T as (
select *, rn=row_number() over(partition by ID,Date order by pos)
from Tbl_TCode
cross apply (select top(Hours) 1 n
from tally
) x
)
select t_P.ID as PersonNum, t_P.Date, t_P.PCode as PayCode,
count(*) as Hours, t_T.TCode as TransferCode
from t_P
join t_T on t_P.ID=t_T.ID and t_P.Date=t_T.Date and t_P.rn=t_T.rn
group by t_P.ID, t_P.Date, t_P.PCode, t_T.TCode
order by t_P.id asc
答案 0 :(得分:4)
更改
cross apply (select top(Hours) 1 n
到
cross apply (select top 1 [Hours] AS n
两个CROSS APPLY语句中的。这只是一个语法错误。