views:

47

answers:

3

I have Following structure

Col1 Col2 Col3  
---------------
F     P    R1
F     P    R2
F     P    R3
F     P    R4

Col3 values can be any thing Now I want in following format only top 3

Col1 Col2 Res1 Res2 Res3  
------------------------------
F     P    R1   R2   R3
A: 

You can do the following:

SELECT Col1, Col2,
    MAX(CASE Col3 WHEN 'R1' THEN 'R1' END) as Res1,
    MAX(CASE Col3 WHEN 'R2' THEN 'R2' END) as Res2,
    MAX(CASE Col3 WHEN 'R3' THEN 'R3' END) as Res3
FROM MyTable
GROUP BY Col1, Col2
bobs
Col3 values are not static then can be any thing. For sample sake I have mentioned it here. I m using sql 2005.
+2  A: 

If using SQL Server 2005+, Oracle 8i+, PostgreSQL 8.4+--you can use analytic functions:

  SELECT x.col1, x.col2,
         MAX(CASE WHEN x.rk = 1 THEN x.col3 END) AS Res1,
         MAX(CASE WHEN x.rk = 2 THEN x.col3 END) AS Res2,
         MAX(CASE WHEN x.rk = 3 THEN x.col3 END) AS Res3
    FROM (SELECT yt.col1,
                 yt.col2,
                 yt.col3,
                 ROW_NUMBER() OVER(PARTITION BY yt.col1, yt.col2
                                       ORDER BY yt.col3) AS rk
            FROM YOUR_TABLE yt) x
GROUP BY x.col1, x.col2
OMG Ponies
Ty very much, it works,Also I was trying to acheive the same in SSRS.
@user420054: I use SSRS, but I always use stored procedures--not matrix/etc, sorry.
OMG Ponies
A: 

What you seek is a dynamic crosstab query that will build columns out of the values in Col3. The SQL language was not designed for dynamic column generation and thus this type of query cannot be done in T-SQL without some fugly dynamic SQL. Instead, I would recommend you build your query in a middle-tier component or use a reporting tool.

Thomas
I'm using SSRS Report 2005 for excel. I tried using Matrix.The problem is how to show Res1,Res2 and Res3 independently so that user has option to sort in excel.
@user420054 - Here's an article about doing something similar using SSRS Matrix. http://www.simple-talk.com/sql/reporting-services/advanced-matrix-reporting-techniques/
Thomas
@user420054 - The other way of course is to write code that builds the query. SSRS is not my specialty but would expect that there is a means to inject some custom code that would build the query using a call to the db and then pass that query to the remainder of the SSRS package. However, again you are outside my area of expertise with SSRS. You might consider opening a new case related to the Matrix component with SSRS as the tag.
Thomas
@Thomas: OP has already opened such a question, here: http://stackoverflow.com/questions/3766227/ssrs-matrix-pivot . I have since suggested an answer to it.
Mark Bannister
@Thomas I have also opened a new ticket for which Mark has an answer. I have not verified it as with sql I m able to resolve and I have not used Matrix, instead using Table and it appears to be pretty fast. Thanks to one and all.