如何将Count(*)与sql连接一起使用

时间:2014-09-29 10:48:48

标签: sql sql-server

我正在尝试在SQL Server 2008中获取行数。我正在使用完美的联接,我只想获得总记录,因为此刻总记录超过了千位。

select 
    tablet.Approach.ApproachId,StartDateTime,QuestionId 
from 
    Tablet.Approach
join 
    tablet.DataCapture on tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
where 
    QuestionId = 25

这样我就可以看到现有结果加上1个显示总行数的额外字段

4 个答案:

答案 0 :(得分:1)

你可以这样实现 -

解决方案:1

SELECT tablet.Approach.ApproachId
    ,StartDateTime
    ,QuestionId
    ,COUNT(*) OVER () AS TotalRowCount
FROM Tablet.Approach
JOIN tablet.DataCapture ON tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
WHERE QuestionId = 25

解决方案:2 (使用CTE)

;WITH SourceData
as
(
    SELECT tablet.Approach.ApproachId
    ,StartDateTime
    ,QuestionId
    FROM Tablet.Approach
    JOIN tablet.DataCapture ON tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
    WHERE QuestionId = 25

)
,RecordCnt
AS
(
    SELECT COUNT(ApproachId) AS TotalRowCount
    FROM SourceData
)
Select * from SourceData Cross join RecordCnt

答案 1 :(得分:0)

试试这个

select
 count(*),
 tablet.Approach.ApproachId,StartDateTime,QuestionId 
 from Tablet.Approach
 join tablet.DataCapture
 on tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
 where QuestionId = 25
 group by tablet.Approach.ApproachId,StartDateTime,QuestionId

答案 2 :(得分:0)

您可以使用窗口函数获取记录总数,尤其是count()

select a.ApproachId, StartDateTime, QuestionId,
       count(*) over () as TotalRows
from Tablet.Approach a join
     tablet.DataCapture dc
     on a.ApproachId = dc.ApproachId
where QuestionId = 25;

我还添加了表别名。这些使查询更容易编写和阅读。

答案 3 :(得分:-1)

 SELECT COUNT(*),tablet.Approach.ApproachId,StartDateTime,QuestionId 
 FROM Tablet.Approach
 JOIN tablet.DataCapture ON tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
 WHERE QuestionId = 25
 GROUP BY tablet.Approach.ApproachId,StartDateTime,QuestionId