按计数对多个结果组进行分组

时间:2014-07-25 08:56:00

标签: sql sql-server

我有一个查询循环一些数据并返回一个计数,如果为true。但是由于循环,计数只计算结果,所以你只得到1,1,1,1返回等...而不是4.

WHILE (@I <= @RowCount)
BEGIN
    DECLARE @forename VARCHAR(50)
    DECLARE @surname VARCHAR(50)
    SELECT @DOB = forename FROM #mytemp WHERE row  = @I
    SELECT @forename = forename FROM #mytemp WHERE row  = @I + 1
    SELECT @surname = forename FROM #mytemp WHERE row  = @I + 2
        SELECT COUNT(*) FROM [FPTDB].dbo.clients WHERE forename = @forename AND surname = @surname AND dob = @DOB
    SET @I = @I  + 3
END

我认为我需要以某种方式对结果集进行分组以计算结果,但我不确定如何。

2 个答案:

答案 0 :(得分:0)

您应该添加另一个变量并将每个循环计数的总和存储在其中。 在循环之后,您可以输出变量值。

DECLARE @tot INT unsigned
SELECT @tot = 0

WHILE (@I <= @RowCount)
BEGIN
    DECLARE @forename VARCHAR(50)
    DECLARE @surname VARCHAR(50)

    SELECT @DOB = forename FROM #mytemp WHERE row  = @I
    SELECT @forename = forename FROM #mytemp WHERE row  = @I + 1
    SELECT @surname = forename FROM #mytemp WHERE row  = @I + 2
        SELECT @tot = @tot + COUNT(*) FROM [FPTDB].dbo.clients WHERE forename = @forename AND surname = @surname AND dob = @DOB
    SET @I = @I  + 3
END

SELECT @tot

答案 1 :(得分:0)

我建议跳过WHILE,你可以这样做(最后的选择没有经过测试):

DECLARE @mytemp TABLE (forename VARCHAR(100))

INSERT INTO @mytemp SELECT 'tom'
INSERT INTO @mytemp SELECT 'bob'
INSERT INTO @mytemp SELECT 'smith'
INSERT INTO @mytemp SELECT 'mary'
INSERT INTO @mytemp SELECT 'tedy'
INSERT INTO @mytemp SELECT 'carry'
INSERT INTO @mytemp SELECT 'wmary'
INSERT INTO @mytemp SELECT 'wtedy'
INSERT INTO @mytemp SELECT 'wcarry'

--ADD surname, forename and DOB numbering to table (column isType)
;WITH mytemp AS (
    SELECT forename, ROW_NUMBER() OVER (ORDER BY forename) as ID
    FROM @mytemp
)
SELECT forename, 
    CASE 
        WHEN ID % 3 = 0 THEN 3 --surname
        WHEN ID % 3 = 2 THEN 2 --forename
        ELSE 1  -- DOB
    END AS isType
INTO #myTemp2
FROM mytemp
ORDER BY ID


/*result like this
forename    ID  isType
bob         1   1
carry       2   2
mary        3   3
smith       4   1
tedy        5   2
tom         6   3
wcarry      7   1
wmary       8   2
wtedy       9   3
*/



--Join just created table 3 times
SELECT COUNT(*) 
FROM [FPTDB].dbo.clients AS C
INNER JOIN #myTemp2 AS T1 --DOB
    ON T1.forename= C.dob 
    AND T1.isType = 1
INNER JOIN #myTemp2 AS T2 --forename
    ON T2.forename = C.forename
    AND T2.isType = 2
INNER JOIN #myTemp2 AS T3 --surname
    ON T3.forename= C.surname 
    AND T3.isType = 3