Avatar of smc1234
 asked on

SQL Crosstab Query

I need to create sql cross-tab report in the attached format which will display only the most recent SubCodeDesc for each main Code based on an effective date.
DB Reporting ToolsMicrosoft SQL Server 2008SQL

Avatar of undefined
Last Comment

8/22/2022 - Mon

SELECT `table`.SubCode, Max(`table`.EffDt)
FROM `table` GROUP BY `table`.SubCode
Kevin Cross

GROUP BY approach might work, but you will have to do a conditional aggregate using CASE. For example, MAX(CASE MainCode WHEN '11111' THEN EffDt END) AS MainCode_11111 will get you the most recent effective date for a given SubCode grouping.

EDIT: I remember now why I was going to suggest PIVOT, you want the SubCodeDesc as the value and not the date. Therefore, I would write your data selection subquery with ROW_NUMBER() windowing function and OVER() analytic clause to rank rows by MainCode-SubCode combinations. When you PIVOT rows with rank = 1, you will get the most recent values of SubCodeDesc.
Kevin Cross

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

here's a demonstration of writing a crosstab query for Excel

Your help has saved me hundreds of hours of internet surfing.
Kevin Cross

@urthrilled, Jet's TRANSFORM syntax will not work in SQL Server. You have to use PIVOT and it works differently (as shown above).

Thanks a lot