0

I need to place some of my results in columns. See below example...

SELECT *
FROM tblAccount
WHERE Code IN ('H20', 'T10')
ORDER BY ID, YearPaid

Results...

ID   YearPaid     Amount   Code   Name
-------------------------------------------
1    2011-01-01    31 50   H20    Service
1    2011-01-01    45 00   T10    Service
2    2011-01-02    31 50   H20    Benefit
2    2011-01-02    45 00   T10    Benefit
3    2011-01-03    31 20   H20    Pay
3    2011-01-03    45 00   T10    Pay

I need the results to be displayed like below...

ID   YearPaid    Amount   Code   Name      Amount   Code
--------------------------------------------------------
1    2011-01-01   31 50   H20    Service    45 00   T10
2    2011-01-02   31 50   H20    Benefit    45 00   T10
3    2011-01-03   31 20   H20    Pay        45 00   T10 

I thought of using a pivot, but I am not aggregating anything.

I could do temp tables for each code, but their has to be a better way.

Any help would be great!

1
  • You can still use a pivot. If you do a sum of a value column but group by the same amount of fields as in the table then your sum essentially just shows your normal data. Same idea here. Commented Oct 7, 2014 at 16:40

1 Answer 1

2

I thought of using a pivot, but I am not aggregating anything, this is not necessarily true, many times when a user says that, you can see that you could use min or max. So, assuming that you can have 2 rows for each ID, YearPaid:

;WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY ID, YearPaid ORDER BY ID) 
    FROM tblAccount
    WHERE Code IN ('H20', 'T10')
)
SELECT  ID, 
        YearPaid,
        MIN(CASE WHEN RN = 1 THEN Amount END) Amount1,
        MIN(CASE WHEN RN = 1 THEN Code END) Code1,
        MIN(CASE WHEN RN = 1 THEN Name END) Name1,
        MIN(CASE WHEN RN = 2 THEN Amount END) Amount2,
        MIN(CASE WHEN RN = 2 THEN Code END) Code2,
        MIN(CASE WHEN RN = 2 THEN Name END) Name2
FROM CTE
GROUP BY ID, 
         YearPaid
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.