0

I have table MailSummary:

Columns:

Send(Int), Reply(Int), SRT(Nvarchar(10)), NAME(Nvarchar(10))

|Send| Reply| SRT| Name|
------------------------
| 100|     8|  10|    B|
|  30|     2|  20|    R|
|   5|     0|  30|    S|
-----------------------

I want to transform the table and get a new result set like:

Sum(Send), Sum(Reply) 

and show the name in columns and the value of SRT under the new columns

|Send| Reply| B | R | S |
-------------------------
| 135|    10| 10| 20| 30|

How can I do it in a SQL query?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user3020789
  • 19
  • 1
  • 4

1 Answers1

1

This works fine for your scenario:

SELECT SUM(Send) as Send,
       SUM(Reply) as Reply,
       MIN(CASE WHEN Name = 'B' THEN SRT END) AS B,
       MIN(CASE WHEN Name = 'R' THEN SRT END) AS R,
       MIN(CASE WHEN Name = 'S' THEN SRT END) AS S
FROM   TEST 

Though for a more dynamic query, you will want a dynamic cross tab query.

Example on fiddle: http://sqlfiddle.com/#!3/d0ddc/12

Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70