在具有UNION的查询中使用OVER()

时间:2015-07-22 18:23:05

标签: sql sql-server

我正在使用Microsoft SQL 2012

我在查询中使用OFFSET和FETCH NEXT进行分页。我确实需要整体计数,我使用OVER()来获得整体计数。我遇到的问题是,当我在其中一个查询中有一个UNION时,OVER()将返回UNION部分的总数。

示例:

SELECT something
      ,overall_count = COUNT(*) OVER()
FROM tbl_something
WHERE something = @someparameter

UNION

SELECT something
      ,overall_count = COUNT(*) OVER()
FROM tbl_something
WHERE something = @someOtherParameter

OFFSET (@intPage - 1) * 50 ROWS
FETCH NEXT 50 ROWS ONLY

在上面的示例中,如果查询中的每个SELECT语句都有10个结果,则对于每个记录,overall_count将返回10。但我需要所有记录的计数。

3 个答案:

答案 0 :(得分:4)

只需要合并2个查询然后获取计数和偏移量

$users = User::with(array('role' => function($query)
{
    $query->orderBy('id', 'DESC');

}))->get();

或者你可以使用cte,如果它更有意义

SELECT *, 
       overall_count = COUNT(*) OVER()
FROM (
    SELECT something
    FROM tbl_something
    WHERE something = @someparameter
    UNION
    SELECT something
    FROM tbl_something
    WHERE something = @someOtherParameter
) u
ORDER BY something
OFFSET (@intPage - 1) * 50 ROWS
FETCH NEXT 50 ROWS ONLY

答案 1 :(得分:1)

您是否尝试过在工会周围附加一份Select Statement?如下......

SELECT * FROM (
   SELECT something
         ,overall_count = COUNT(*) OVER()
   FROM tbl_something
   WHERE something = @someparameter

   UNION

   SELECT something
         ,overall_count = COUNT(*) OVER()
   FROM tbl_something
   WHERE something = @someOtherParameter
) a

ORDER BY something
OFFSET (@intPage - 1) * 50 ROWS
FETCH NEXT 50 ROWS ONLY

答案 2 :(得分:0)

SELECT something
      ,overall_count = COUNT(*) OVER()
FROM tbl_something
WHERE something in (@someparameter, someOtherParameter) 
order by something 
OFFSET (@intPage - 1) * 50 ROWS
FETCH NEXT 50 ROWS ONLY