查找使用Order by选择查询的总行数

时间:2016-07-12 08:38:09

标签: sql sql-server sql-server-2008

我有以下查询,我想将总行数统计为@TotalRows

Declare @TotalRows int

@TotalRows = Count(Select distinct 
                       a.id as apptID, i.Insurancename, InsDtl.Insurenceclassification
                   From 
                       Appointment A    
                   Left Outer join 
                       Insuarancedetails InsDtl WITH (NOLOCK) on InsDtl.AppId  = A.ID
                   Left Outer join 
                       Insurance i WITH (NOLOCK) on i.ID = InsDtl.Insurencepayer
                   order by 
                       apptID, Insurancename)

我尝试过使用Count(*)Row_Number(),但它并没有匆匆忙忙。它说子命令不允许使用order by子句。

3 个答案:

答案 0 :(得分:1)

您可以在select语句后立即使用@@ rowcount来获取受影响的行,

DECLARE @TotalRows INT

Select distinct a.id as apptID, i.Insurancename, InsDtl.Insurenceclassification
From Appointment A    
  Left Outer join Insuarancedetails InsDtl WITH (NOLOCK) on InsDtl.AppId  = A.ID
  Left Outer join Insurance i WITH (NOLOCK) on i.ID = InsDtl.Insurencepayer
 ORDER BY apptID,Insurancename

SELECT @TotalRows = @@ROWCOUNT

答案 1 :(得分:1)

试试这个

SELECT
     A.apptID, 
     A.Insurancename, 
     A.Insurenceclassification,
     COUNT(A.TmpColumn) OVER (PARTITION BY A.TmpColumn) AS CountOfRow
FROM
(
    SELECT distinct 
        a.id as apptID, 
        i.Insurancename, 
        InsDtl.Insurenceclassification,
        1 AS TmpColumn
    FROM 
        Appointment A Left Outer join 
        Insuarancedetails InsDtl WITH (NOLOCK) on InsDtl.AppId  = A.ID  Left Outer join 
        Insurance i WITH (NOLOCK) on i.ID = InsDtl.Insurencepayer    
) A
ORDER BY 
    A.apptID,
    A.Insurancename

已更新,因为问题已更新

DECLARE @TotalRows INT

SELECT
    @TotalRows = COUNT(A.apptID)
FROM
(
    SELECT DISTINCT 
        a.id as apptID, 
        i.Insurancename, 
        InsDtl.Insurenceclassification
    FROM 
        Appointment A   LEFT OUTER JOIN 
        Insuarancedetails InsDtl WITH (NOLOCK) on InsDtl.AppId  = A.ID LEFT OUTER JOIN 
        Insurance i WITH (NOLOCK) on i.ID = InsDtl.Insurencepayer
 ) A

答案 2 :(得分:0)

Distinct意味着分组依据,因此将查询更改为分组依据并使用计数..

   select a.id , i.Insurancename, InsDtl.Insurenceclassification,count(*) as cnt
    From Appointment A    
    Left Outer join 
    Insuarancedetails InsDtl WITH (NOLOCK) on InsDtl.AppId  = A.ID
     Left Outer join 
    Insurance i WITH (NOLOCK) on i.ID = InsDtl.Insurencepayer
    group by a.id, i.Insurancename, InsDtl.Insurenceclassification
     ORDER BY apptID,Insurancename