I’m working on an SQL problem and I’m stuck. The task is about renumbering unique pairs of maker and type from a Product table. Here’s what I need to do:
Order by manufacturer name (ascending)
Order product types as PC, Laptop, Printer
Show manufacturer name only in the first row for each maker
My current query looks like this:
SELECT
ROW_NUMBER() OVER (ORDER BY
manufacturer ASC,
CASE product_type
WHEN 'Desktop' THEN 1
WHEN 'Notebook' THEN 2
WHEN 'Printing' THEN 3
END
) AS row_num,
manufacturer, product_type
FROM inventory
ORDER BY manufacturer,
CASE product_type
WHEN 'Desktop' THEN 1
WHEN 'Notebook' THEN 2
WHEN 'Printing' THEN 3
END
But my output isn’t correct. It’s not grouping manufacturers or showing empty strings for repeated makers. Any ideas on how to fix this? I’m using SQL Server 2012 for this exercise.
Your approach is sound, but you need a few adjustments to achieve the desired result. Consider using DENSE_RANK() instead of ROW_NUMBER() to handle the unique pairs. For the manufacturer name, you can employ a window function with FIRST_VALUE(). Here’s a modified version of your query:
SELECT
DENSE_RANK() OVER (ORDER BY manufacturer, CASE product_type WHEN ‘Desktop’ THEN 1 WHEN ‘Notebook’ THEN 2 WHEN ‘Printing’ THEN 3 END) AS row_num,
CASE WHEN ROW_NUMBER() OVER (PARTITION BY manufacturer ORDER BY product_type) = 1 THEN manufacturer ELSE ‘’ END AS manufacturer,
product_type
FROM inventory
ORDER BY manufacturer, CASE product_type WHEN ‘Desktop’ THEN 1 WHEN ‘Notebook’ THEN 2 WHEN ‘Printing’ THEN 3 END
This should give you the correct grouping and empty strings for repeated manufacturers. Let me know if you need further clarification.