如何检索总计数

时间:2016-09-09 10:37:05

标签: sql-server stored-procedures sql-server-2008-r2

这是在SQL Server中运行的存储过程。我还想提出返回数据的总数。

ALTER PROCEDURE [dbo].[spManufacturerdata]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
SELECT [t1].[OEMName] AS [oem], [t1].[OemId] AS [id]
FROM (
    SELECT DISTINCT [t0].[OEMName], [t0].[OemId]
    FROM [dbo].[tblOEM] AS [t0]
    WHERE [t0].[IsActive] = 1
    ) AS [t1]
order BY LOWER([t1].[OEMName])

END

提前致谢。

4 个答案:

答案 0 :(得分:0)

添加分组依据

SELECT COUNT([t1].[OemId]) AS TotalCount,[t1].[OEMName] AS [oem], [t1].[OemId] AS [id]
FROM (
    SELECT DISTINCT [t0].[OEMName], [t0].[OemId]
    FROM [dbo].[tblOEM] AS [t0]
    WHERE [t0].[IsActive] = 1
    ) AS [t1]
GROUP BY [t1].[OEMName] , [t1].[OemId] 
order BY LOWER([t1].[OEMName])

答案 1 :(得分:0)

我意识到COUNT()COUNT(DISTINCT)每行只会返回1。

如果你想要所有行的总计数,那么你想要这样的东西:

SELECT t.OEMName as oem, t.OemId as id,
       SUM(COUNT(*)) OVER () as total_rows,
       COUNT(*) OVER () as total_combinations
FROM dbo.tblOEM t
WHERE t.IsActive = 1
GROUP BY t.OEMName, t.OemId
ORDER BY LOWER(t.OEMName);

答案 2 :(得分:0)

我不确定我是否了解你。 如果要计算上一个select返回的总记录数,只需要调用count():

SELECT COUNT([t1].[OEMName]) AS totalRowsInPreviuosQuery
FROM (
    SELECT DISTINCT [t0].[OEMName], [t0].[OemId]
    FROM [dbo].[tblOEM] AS [t0]
    WHERE [t0].[IsActive] = 1
) AS [t1]

答案 3 :(得分:0)

试试这个,

SELECT count(*) AS TotalCount
FROM (
    SELECT DISTINCT [t0].[OEMName]
        ,[t0].[OemId]
    FROM [dbo].[tblOEM] AS [t0]
    WHERE [t0].[IsActive] = 1
    ) AS [t1]