SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


A Cross Tab query, sort of....


A Cross Tab query, sort of....

Author
Message
SeanF-708538
SeanF-708538
Right there with Babe
Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)

Group: General Forum Members
Points: 715 Visits: 465
Hi Experts,

It's Friday afternoon here in NZ and I'm looking at some code, that works fine, thinking "there's got to be a more elegant solution",
but after pulling out what little hair I have left I thought I would use my "ask a friend" option, so....

We have a set of data, where a Customer always has at least one Tariff attached and potentially four. Each Record / Tariff combination is a sperate row in a table. So the data appears like this [we have a little shy of 100,000 records in this table] -


Customer Tariff TariffOrder
Record1 121 1
Record1 171 2
Record1 171 3
Record2 121 1
Record2 171 2
Record3 121 1
Record4 101 1
Record5 101 1
Record5 151 2
Record5 171 3
Record5 171 4
Record6 121 1
Record6 171 2
Record7 101 1
Record8 101 1
Record8 171 2
Record8 171 3
Record9 101 1
Record10 171 1


But we have a requirement to report on the distinct combinations, so the report looks like this -


Count tariff1 tariff2 tariff3 tariff4
3 101 NULL NULL NULL
1 101 151 171 171
1 101 171 171 NULL
1 121 NULL NULL NULL
2 121 171 NULL NULL
1 121 171 171 NULL
1 171 NULL NULL NULL


I've achieved this using a Temp table and a couple of update statements that performs adequately, but is there another solution? Perhaps one that could be flexible with the number of combinations?

We are using SQL 2008 r2.

Thank you for your time!

And some code to create a limited set of sample data -


create table #Cust
(
Customer char(10) not null,
Tariff char(3) not null,
TariffOrder tinyint not null
)

insert into #Cust (Customer, Tariff, TariffOrder) values
('Record1', '121', 1),
('Record1', '171', 2),
('Record1', '171', 3),
('Record2', '121', 1),
('Record2', '171', 2),
('Record3', '121', 1),
('Record4', '101', 1),
('Record5', '101', 1),
('Record5', '151', 2),
('Record5', '171', 3),
('Record5', '171', 4),
('Record6', '121', 1),
('Record6', '171', 2),
('Record7', '101', 1),
('Record8', '101', 1),
('Record8', '171', 2),
('Record8', '171', 3),
('Record9', '101', 1),
('Record10', '171', 1)


dwain.c
dwain.c
SSCoach
SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)

Group: General Forum Members
Points: 18335 Visits: 6431
I'm no expert, but can I still reply?

What you need is a crosstab query, which is pretty straightforward given a known number of tariffs and the fact that you even supplied a tariff order column.


SELECT Customer, Count=COUNT(*)
,tariff1=MAX(CASE TariffOrder WHEN 1 THEN Tariff END)
,tariff2=MAX(CASE TariffOrder WHEN 2 THEN Tariff END)
,tariff3=MAX(CASE TariffOrder WHEN 3 THEN Tariff END)
,tariff4=MAX(CASE TariffOrder WHEN 4 THEN Tariff END)
FROM #Cust
GROUP BY Customer




Very nice job of posting DDL, sample data and expected results by the way.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
dwain.c
dwain.c
SSCoach
SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)

Group: General Forum Members
Points: 18335 Visits: 6431
Duplicate post deleted.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
dwain.c
dwain.c
SSCoach
SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)SSCoach (18K reputation)

Group: General Forum Members
Points: 18335 Visits: 6431
Duplicate post deleted.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
SeanF-708538
SeanF-708538
Right there with Babe
Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)

Group: General Forum Members
Points: 715 Visits: 465
Hi Dwain,

Thanks for your reply, it's not quite what I'm after though.... Your solution appears to provide a count of the Tariffs for each Customer, I need to get a count of the Customers with a particular combination of Tariff. So from the sample data I would expect 7 rows with a count of the various Tariff combinations not 10, being the count of distinct Customers.

Thanks for the post
Jeff Moden
Jeff Moden
SSC Guru
SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)

Group: General Forum Members
Points: 220970 Visits: 42002
This will do it. If you want the NULLs to show up instead of the blanks, just remove the ELSE '' from each line where it appears.

WITH 
cteCrossTab AS
(
SELECT Customer,
Tariff1 = MAX(CASE WHEN TariffOrder = 1 THEN Tariff ELSE '' END),
Tariff2 = MAX(CASE WHEN TariffOrder = 2 THEN Tariff ELSE '' END),
Tariff3 = MAX(CASE WHEN TariffOrder = 3 THEN Tariff ELSE '' END),
Tariff4 = MAX(CASE WHEN TariffOrder = 4 THEN Tariff ELSE '' END)
FROM #Cust
GROUP BY Customer
)
SELECT [Count] = COUNT(*),
Tariff1, Tariff2, Tariff3, Tariff4
FROM cteCrossTab
GROUP BY Tariff1, Tariff2, Tariff3, Tariff4
ORDER BY Tariff1, Tariff2, Tariff3, Tariff4
;



Results from the given data in the original post:

Count       Tariff1 Tariff2 Tariff3 Tariff4
----------- ------- ------- ------- -------
3 101
1 101 151 171 171
1 101 171 171
1 121
2 121 171
1 121 171 171
1 171

(7 row(s) affected)


--Jeff Moden

RBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.
First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
SeanF-708538
SeanF-708538
Right there with Babe
Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)Right there with Babe (715 reputation)

Group: General Forum Members
Points: 715 Visits: 465
Jeff,

Thank you for the elegant solution I was after.

Intrigued, I added this code into a stored procedure and compared the performance against the existing, the average over 10 runs indicates that Jeff's solution is approximately twice as fast. Nice one!

Thank you
Jeff Moden
Jeff Moden
SSC Guru
SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)SSC Guru (220K reputation)

Group: General Forum Members
Points: 220970 Visits: 42002
SeanF-708538 (9/23/2012)
Jeff,

Thank you for the elegant solution I was after.

Intrigued, I added this code into a stored procedure and compared the performance against the existing, the average over 10 runs indicates that Jeff's solution is approximately twice as fast. Nice one!

Thank you



Heh... twice as fast? I'm slipping up in my old age. :-P

Thanks for the feedback, Sean.

--Jeff Moden

RBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.
First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search