6

SELECT Name1, Name2, Value FROM mytable gives me the following result set:

Name1 Name2 Value
A     P1     1
A     P2     1
A     P3     2
B     P1     3
B     P2     1
B     P4     1

How do I translate that to:

       A     B
P1     1     4
P2     1     1
P3     2     null
P4     null  1

Thanks,

8
  • 1
    Hi @user! What DBMS are you using? Aug 24, 2011 at 20:54
  • Are A and B a fixed list of constants?
    – Neil
    Aug 24, 2011 at 20:58
  • 1
    A and B are not fixed, the top select could return more than just A and B, sometimes it will be A, B, C, ... X for instance.
    – user683302
    Aug 24, 2011 at 21:02
  • 2
    @jadarnel27 wasn't your fault, the question wasn't tagged with sql-server-2005 until Tony edited it, and just because the OP happened to use the keyword PIVOT doesn't necessarily mean they know it's only available in 2005+. Lots of people ask HOW DO I PIVOT THIS? when they're using SQL Server 2000. :-) Aug 24, 2011 at 21:18
  • 2
    @user683302 I think that's important information that should be part of the question - it's not clear that there may be other values other than A and B. Also what happens when there are two rows like this: A, P1, 1 and A, P1, 4? Detailing the unique constraints on the table will help others determine how to aggregate if necessary. Aug 24, 2011 at 21:22

3 Answers 3

10

Since you are using SQL Server 2005, here is the code:

DECLARE @cols VARCHAR(1000)
DECLARE @sqlquery VARCHAR(2000)

SELECT  @cols = STUFF(( SELECT distinct  ',' + QuoteName([Name1])
                        FROM myTable FOR XML PATH('') ), 1, 1, '') 


SET @sqlquery = 'SELECT * FROM
      (SELECT Name2, Name1, Value
       FROM myTable ) base
       PIVOT (Sum(Value) FOR [Name1]
       IN (' + @cols + ')) AS finalpivot'

EXECUTE ( @sqlquery )

This will work no matter how many different status you have. It dynamically assembles a query with PIVOT. The only way you can do PIVOT with dynamic columns is by assembling the the query dynamically, which can be done in SQL Server.

Other examples:

2
4

I don't have SQL Server running here at work so this may not by completely syntatically correct but one approach would be cross tabulation

SELECT name2
     , SUM(CASE WHEN name1 = 'A' THEN value END) AS A
     , SUM(CASE WHEN name1 = 'B' THEN value END) AS B
FROM table
GROUP BY name2

For variable number of columns you could use dynamic SQL:

DECLARE @sql varchar(max)
SELECT @sql = COALESCE(@sql+',','') + 'SUM(CASE WHEN nane1 = '''+name1+''' THEN value END) AS ['+name1']' FROM table

SET @sql = 'SELECT name2, '+@sql+' FROM table GROUP BY name2'

EXEC(@sql)
1
  • 2
    There are much more constructive things you can do while your code is compiling ;) I posted that comment while I was at work as well haha Aug 25, 2011 at 14:13
2

You can use a PIVOT clause. Your query could be something like this:

WITH Source as (
    SELECT Name1, Name2, [Value]
    FROM mytable 
)

SELECT Name2, CASE WHEN A IS NOT NULL THEN A ELSE 'your string' END As A
, CASE WHEN B IS NOT NULL THEN B ELSE 'your string' END As B
FROM (
        SELECT Name2, Name1, [Value]
        FROM Source
) s
PIVOT 
(
    MAX([Value]) FOR Name1 IN (A, B) -- any other Name1 would go here
) p

using your sample data above, my results were

P1  1           3
P2  1           1
P3  2           your string
P4  your string 1

EDIT:

Since you have an unknown number of columns, you will need to look at using dynamic SQL and there are several answers here on SO about that with PIVOT.

SQL Server 2005 Pivot on Unknown Number of Columns

Pivot Table and Concatenate Columns

5
  • The issue is the OP cannot limit the output to A, B. There may also be C, ..., X, as he stated in one of the comments. Aug 24, 2011 at 21:21
  • I made a few modifications and was able to get it to work by using this example and stackoverflow.com/questions/159456/…. One last thing, how would I go about replacing the NULLs with another String. I tried a CASE but it only replaces the 'Value' fields that have values, not the NULLs
    – user683302
    Aug 24, 2011 at 23:02
  • I updated the above PIVOT query using CASE and is changes the NUll values to a string.
    – Taryn
    Aug 24, 2011 at 23:10
  • I would prefer COALESCE over CASE in this situation, otherwise it's nice.
    – Andriy M
    Aug 24, 2011 at 23:46
  • @Andriy I use COALESCE too in a lot of situations. I have gotten flack for using it on here before so I used CASE this time.
    – Taryn
    Aug 24, 2011 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.