2016-07-12 54 views
0

我有以下查詢,我想計算總行數爲@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()但它不是wotking。它表示子查詢不允許使用order by子句。

+0

你能告訴我的結果應該如何看起來像 –

+0

我只需要計數,並在一個聲明變量中設置該計數。 – Hitesh

+0

select @ TotalRows = count(*)from(your query here)T – nazark

回答

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 
+0

@Hitesh答案已更新。請再次檢查。 – NEER

+0

感謝Hebele的回覆 – Hitesh

0

鮮明的暗示集團,因此通過和使用增減數查詢組..

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 
1

您可以立即使用@@ ROWCOUNT select語句後獲得受影響的行,

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 
+0

它工作正常,但我使用@TotalRows在我的主要查詢在相同的存儲過程因此,使用您的查詢它也顯示上述查詢的結果。請任何幫助。 – Hitesh