SQL Server在Offset上进行多次选择...获取...下一个查询

时间:2018-04-24 02:33:08

标签: sql-server datatables offset

我正在尝试通过服务器端处理将数据存入数据表(数据表的js库)。

数据应按以下方式生成

+---------+--------+--------+
|  Name   | TotalA | TotalB |
+---------+--------+--------+
| Person1 |     10 |     40 |
+---------+--------+--------+

我试过的查询

select 
    a.Name,
    (select count(*) from SummaryA where id = a.id) as TotalA,
    (select count(*) from SummaryB where id = a.id) as TotalB
from
    records a
order by 
    a.Name
    offset 0 rows fetch next 10 rows only

select
    aa.Name,
    (select count(*) from SummaryA where id = aa.id) as TotalA,
    (select count(*) from SummaryB where id = aa.id) as TotalB
from 
    (select 
         a.Name, a.id
     from 
         records a
     order by 
         a.Name
         offset 0 rows fetch next 10 rows only) as aa

但是,这些查询将导致如下错误

  

查询错误:FETCH语句中NEXT选项的使用无效。

在查询下运行不是问题

select 
    a.Name
from
    records a
    offset 0 rows fetch next 10 rows only

1 个答案:

答案 0 :(得分:1)

Issue-offset_row_count_expression可以是变量,参数或常量标量子查询。使用子查询时,它不能引用外部查询范围中定义的任何列。  link

尝试

    ;with temp as (select a.name ,
     count(b.id) as TotalA ,
    count(c.id) as Totalb
FROM records a
   left join  SummaryA b
      b.id=a.id
  left join SummaryB  c
      c.id=a.id
group by a.name)

select * from temp
order by temp.Name
Offset 0 rows
fetch next 10 rows only

这也可以解决

 with tmp as (
    select a.name ,
         a.id
    FROM records a
    order by temp.Name
    Offset 0 rows
    fetch next 10 rows only
    )

    select a.name ,
         count(b.id) as TotalA ,
        count(c.id) as Totalb
    FROM tmp a
       left join  SummaryA b
          b.id=a.id
      left join SummaryB  c
          c.id=a.id
    group by a.name order by a.Name