[英]How to use Count(*) with sql joins
I am trying to get row count in SQL Server 2008. I am using join which works perfect, I just want to get the total records because at the moment total records go beyond thousand. 我正在尝试在SQL Server 2008中获得行数。我使用的连接效果很好,我只想获取总记录,因为目前总记录已超过1000。
select
tablet.Approach.ApproachId,StartDateTime,QuestionId
from
Tablet.Approach
join
tablet.DataCapture on tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
where
QuestionId = 25
So that I can see the existing result plus 1 extra field which displays total number of rows 这样我就可以看到现有结果以及1个额外的字段,该字段显示总行数
You can achieve it like this - 您可以这样实现-
Solution: 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
Solution: 2 (Using CTE) 解决方案: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
try this 尝试这个
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
You can get the total number of records using window functions, in particular count()
: 您可以使用窗口函数来获取记录总数,尤其是
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;
I also added table aliases. 我还添加了表别名。 These make the query easier to write and to read.
这些使查询更易于编写和阅读。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.