I have the following sales table (SQL Server 2017) (for each good is about 20 rows):
+---------+----------+-------------+-------+---------+------+
| good_id | store_id | week_number | promo | holiday | sale |
+---------+----------+-------------+-------+---------+------+
| 201712 | 255 | 1 | 1 | 0 | 2 |
+---------+----------+-------------+-------+---------+------+
| 201712 | 255 | 2 | 0 | 0 | 0 |
+---------+----------+-------------+-------+---------+------+
I want to prepare a dataset so that each good in a particular store corresponds to one row:
+---------+----------+---------------+---------------+---------+---------+-----------+-----------+--------+--------+
| good_id | store_id | week_number_1 | week_number_2 | promo_1 | promo_2 | holiday_1 | holiday_2 | sale_1 | sale_2 |
+---------+----------+---------------+---------------+---------+---------+-----------+-----------+--------+--------+
| 201712 | 255 | 1 | 2 | 1 | 0 | 0 | 0 | 2 | 0 |
+---------+----------+---------------+---------------+---------+---------+-----------+-----------+--------+--------+
I know how to do this for a single column with unique values:
SELECT *
FROM
(
SELECT [good_id],
[store_id],
[week_number],
[sale]
FROM table
WHERE good_id = 201712
AND store_id = 255
) AS SourceTable PIVOT(AVG([sale]) FOR [week_number] IN([1],
[2])) AS PivotTable
But how can I write the code I need, I can’t understand yet