且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按ms sql server中的列和行值求和

更新时间:2023-01-28 16:53:31

看看例子:

Have a look at example:
DECLARE @tmp TABLE (Id INT IDENTITY(1,1),  CorrectOption INT,  OptionAnswered INT,  RelationId INT)

INSERT INTO @tmp (CorrectOption, OptionAnswered, RelationId)
VALUES(2, 4, 10), (1, 1, 10), (1, 2, 10), (3, 3, 10), (4, 4, 10)


SELECT RelationId, ProperAnswers, CountOfAnswers, CONVERT(INT, (CONVERT(DECIMAL(8,2), ProperAnswers)/CONVERT(DECIMAL(8,2),CountOfAnswers))*100) + '%' AS [%]
FROM (
    SELECT t1.RelationId, COUNT(t1.RelationId) As CountOfAnswers, t2.ProperAnswers
    FROM @tmp AS t1 INNER JOIN (
        SELECT RelationId, COUNT(RelationId) AS ProperAnswers
        FROM @tmp
        WHERE CorrectOption = OptionAnswered
        GROUP BY RelationId
        ) AS t2 ON t1.RelationId  = t2.RelationId
    GROUP BY t1.RelationId, t2.ProperAnswers
    ) AS T





结果:



Result:

Rel..   PropA   CountA  %
10	3	5	60%