Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about the merits of Pivot vs Case

I have a query that returns attributes of an object. What I want is to have attributes pivoted into the table. I have seen pivot tables used to do something like this but only where aggregate functions are performed on the cols in the pivot. I have also seen case statements used to do the same thing.

Since you have to manually write out each column in a pivot it's the amount of work for each is relatively the same. What are the advantage and limitations of one over the other?

like image 356
QueueHammer Avatar asked Dec 28 '22 00:12

QueueHammer


1 Answers

I agree with Ken. I never remember the PIVOT syntax without referrring to BOL and additionally it is less flexible than the old school case statement. You can only have one aggregate meaning it is not possible to do something like.

SELECT COUNT(CASE WHEN foo='bar' THEN foo END) AS bar_count,
         SUM(CASE WHEN foo='bar' THEN foo END)  AS bar_sum
FROM your_table     
like image 116
Martin Smith Avatar answered Jan 05 '23 00:01

Martin Smith