簡體   English   中英

如何獲取SQL Server中的聯接表的計數?

[英]How to get the count of a join table in sql server?

我正在使用現有的SQL Server語句:

select 
    rs.record_StepID, rs.recordID, rs.stepTypeID, 
    rs.label, rs.assignedToUserID, rs.stepActivatedDate,
    si.scheduledInspectionID, 
    l.streetNo, l.streetName, l.unit, l.city, l.state, 
    l.postalCode, l.country, rt.categoryName 
from 
    Record_Steps as rs 
left join 
    Users as u on rs.assignedToUserID = u.userID 
left join 
    ScheduledInspections as si on rs.record_StepID = si.record_StepID 
left join 
    Records as r on r.recordID = rs.recordID 
left join 
    Locations as l on l.locationID = r.locationID 
left join 
    recordTypes as rt on r.recordTypeID = rt.recordTypeID 
where  
    (rs.stepTypeID = 1 and rs.status = 1 and rs.assignedToUserID = '3200') 
    or 
    (rs.stepTypeID = 6 and rs.status = 1 and rs.assignedToUserID = '3200') 
    or 
    (rs.stepTypeID = 4 and rs.status = 1  and si.inspectorUserID = '3200' 
     and si.inspectionDate IS NOT NULL 
     AND CAST(si.inspectionDate AS DATE) <= CONVERT(DATE,'2014-9-8')) 
order by 
    stepActivatedDate asc

我現在要做的就是獲取此語句檢索的記錄數。 我將需要設置一個條件來決定何時獲取計數以及何時獲取實際數據,但是現在我需要首先獲取計數,然后在客戶端確認后獲取數據。

我對mysql較為熟悉,因此我希望select count(*) from (select * from users)獲取類似select count(*) from (select * from users) ,但是任何允許我僅獲取count的更改,因為該語句的返回值將對我有很大幫助。

我試着做

select count(*) from ( <copy paste statement>) 

無濟於事。

這應該工作。 我從您的派生表中刪除了order by ,因為這將導致錯誤,並且還為派生表提供了別名。

select count(1) as Cnt
from
(
    select rs.record_StepID, rs.recordID, rs.stepTypeID, rs.label, rs.assignedToUserID, rs.stepActivatedDate,si.scheduledInspectionID, l.streetNo,l.streetName, l.unit, l.city, l.state, l.postalCode, l.country, rt.categoryName 
    from Record_Steps as rs 
    left join Users as u on rs.assignedToUserID = u.userID 
    left join ScheduledInspections as si on rs.record_StepID=si.record_StepID 
    left join Records as r on r.recordID = rs.recordID 
    left join Locations as l on l.locationID = r.locationID 
    left join recordTypes as rt on r.recordTypeID = rt.recordTypeID 
    where (rs.stepTypeID = 1 and rs.status=1 and rs.assignedToUserID = '3200') 
    or (rs.stepTypeID = 6 and rs.status=1 and rs.assignedToUserID = '3200') 
    or (rs.stepTypeID = 4 and rs.status = 1  and si.inspectorUserID = '3200' and si.inspectionDate is not NULL and CAST(si.inspectionDate AS DATE) <= CONVERT(DATE,'2014-9-8')) 
)  as aTable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM