Pivoting Data twice with dynamic sql and custom column names
I have a simple table of non-unique account numbers, product IDs, and quantities: For example: account|productid|qty 1 100 1 1 100 1.5 1 102 6 2 100 1 I'm trying to get this to be pivoted dynamically into this kind of structure: account|product1|qty1|product2|qty2|etc..|etc.. 1 100 2.5 102 6 NULL NULL 2 100 1 NULL NULL NULL NULL Some of these customers can have ordered hundreds of different products, so trying to hard-code things ended up being out of the question. I've managed to pivot this into a table like account|100|102 1 2.5 6 2 1 NULL with product IDs as column headers, with: DECLARE