2
SELECT * from
  (
    SELECT intUserID as [KidId], intAssessmentID as [assid] ,vchTopic as [Topics] from ManageAssessment WHERE intUserID=174 and IsRorW='yes'

   )AS S
  pivot
  (
  COUNT(KidId)

    FOR assid IN ([22],[19],[16],[17],[18])
   )AS s

Hey its my code to create a Table i want to add other columns but it coming wrongly..! i want a column after column 4 i.e, difference of 2 value.can anyone help me to solve.. Thank you.....enter image description here

[

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
user2783430
  • 169
  • 1
  • 4
  • 13

1 Answers1

2

You can do this:

SELECT 
  Topics,
  [22],
  [19],
  [16],
  [17],
  [18],
  [22] - [19] AS NewColumn      
from
(
   SELECT 
     intUserID as [KidId], 
     intAssessmentID as [assid] ,
     vchTopic as [Topics] 
   from ManageAssessment 
   WHERE intUserID=174 and IsRorW='yes'
)AS S
pivot
(
  COUNT(KidId)
  FOR assid IN ([22], [19], [16], [17], [18])
)AS s;

Update:

If you want to add a new row as a total for all new columns, you can do something like this:

WITH CTE AS
(
    SELECT 
      Topics,
      [22],
      [19],
      [16],
      [17],
      [18],
      [22] - [19] AS NewColumn      
    from
    (
       SELECT 
         intUserID as [KidId], 
         intAssessmentID as [assid] ,
         vchTopic as [Topics] 
       from ManageAssessment 
       WHERE intUserID=174 and IsRorW='yes'
    )AS S
    pivot
    (
      COUNT(KidId)
      FOR assid IN ([22], [19], [16], [17], [18])
    )AS s
)
SELECT
  Topics,
  [22],
  [19],
  [16],
  [17],
  [18],
  NewColumn    
FROM CTE
UNION ALL
SELECT
  'Total',
  SUM([22]),
  SUM([19]),
  SUM([16]),
  SUM([17]),
  SUM([18]),
  SUM(NewColumn)
FROM CTE;
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
  • yes Sir,http://stackoverflow.com/questions/9595157/sql-pivot-table-with-column-and-row-totals, i have checked this i could not able meet my requirement,and i cant delete temp table from there,sir if you have any solution you can send me...thank you. – user2783430 Jan 02 '14 at 07:26
  • @user2783430- Sorry but I can't understand your requirement, do you want to add a new column or a new row? Please edit your question and explain what are you trying to do with some samples. – Mahmoud Gamal Jan 02 '14 at 07:28
  • @user2783430 - You're welcome any time, Feel free to ask for any more questions any time, good luck :) – Mahmoud Gamal Jan 02 '14 at 07:48
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/44304/discussion-between-user2783430-and-mahmoud-gamal) – user2783430 Jan 02 '14 at 08:11