sql >> Databasteknik >  >> RDS >> Sqlserver

SQL Server 2005 procentandel inom parentes i pivottabell

Du kan formatera resultatet av din pivotfråga som du skulle göra med alla andra. Så du kan sammanfoga procent till dess respektive källa. Här är en SQL-FIDDLE .

SELECT RC.lessonid AS 'lessonid     response count->'
  , convert (varchar(20), isnull([0], 0))
  + isnull (' ('
-- As both numbers are integers don't forget to cast one of them into double
-- If you dislike * 100 format or want more precise result.
  + convert (varchar(20), [0] * 100 / RCN.N)
  + '%)', '') as [0]
  , convert (varchar(20), isnull([1], 0))
  + isnull (' ('
  + convert (varchar(20), [1] * 100 / RCN.N)
  + '%)', '') as [1]
  , convert (varchar(20), isnull([2], 0))
  + isnull (' ('
  + convert (varchar(20), [2] * 100 / RCN.N)
  + '%)', '') as [2]
  , convert (varchar(20), isnull([3], 0))
  + isnull (' ('
  + convert (varchar(20), [3] * 100 / RCN.N)
  + '%)', '') as [3]
  , convert (varchar(20), isnull([4], 0))
  + isnull (' ('
  + convert (varchar(20), [4] * 100 / RCN.N)
  + '%)', '') as [4]
  ,RCN.N
FROM (
    SELECT lessonid
        ,response
        ,count(response) AS respcnt
    FROM tblRChoices
    GROUP BY lessonid
        ,response
    ) TableResponseCount
PIVOT(SUM(respcnt) FOR response IN (
            [0]
            ,[1]
            ,[2]
            ,[3]
            ,[4]
            )) RC
JOIN (SELECT lessonid, count(lessonid) as N FROM tblRChoices GROUP BY lessonid) RCN 
ON RC.lessonid = RCN.lessonid


  1. Hur man refererar till en kolumn efter ID eller indexnummer

  2. Vad betyder INTERVAL=0 i Oracle Schedular?

  3. Dynamisk borttagning i Oracle

  4. Möjligt att ange unikt index med NULL tillåtna i Rails/ActiveRecord?