Kod: Zaznacz cały
+---------------------------+-----------+-----------+
| Data | Nazwa | Ilosc |
+---------------------------+-----------+-----------+
| 2019-11-06 00:00:00.000 | Towar 1 | 10 |
| 2019-11-03 00:00:00.000 | Towar 2 | 2 |
| 2019-10-29 00:00:00.000 | Towar 1 | 24 |
| 2019-10-27 00:00:00.000 | Towar 2 | 8 |
| 2019-10-26 00:00:00.000 | Towar 3 | 5 |
| 2019-10-21 00:00:00.000 | Towar 1 | 7 |
| 2019-10-18 00:00:00.000 | Towar 2 | 19 |
| 2019-10-14 00:00:00.000 | Towar 1 | 4 |
| 2019-10-12 00:00:00.000 | Towar 2 | 12 |
| 2019-10-07 00:00:00.000 | Towar 1 | 26 |
| 2019-10-05 00:00:00.000 | Towar 2 | 18 |
| 2019-10-04 00:00:00.000 | Towar 3 | 9 |
+---------------------------+-----------+-----------+
Kod: Zaznacz cały
+-----------+-----------+
| Nazwa | Ilosc |
+-----------+-----------+
| Towar 1 | 10 |
| Towar 2 | 2 |
+-----------+-----------+
Kod: Zaznacz cały
+-----------+-----------+-----------+-----------+
| Nazwa | Tydz -1 | Tydz -2 | Tydz -3 |
+-----------+-----------+-----------+-----------+
| Towar 1 | 10 | 2 | NULL |
| Towar 2 | 24 | 8 | 5 |
| Towar 3 | NULL | 7 | 19 |
+-----------+-----------+-----------+-----------+
Kod: Zaznacz cały
IF OBJECT_ID('moja.dbo.tymczasowa', 'U') IS NOT NULL
DROP TABLE moja.dbo.tymczasowa;
SELECT
MIN(datepart(wk, V.dok_DataWyst)) Tydzien, T.tw_nazwa Nazwa, SUM(V.ob_IloscMag * V.ob_Znak) Suma
INTO nasza.dbo.tymczasowa
FROM subiekt.dbo.vwZstSprzWgKhnt V
LEFT JOIN subiekt.dbo.tw__Towar T ON T.tw_id = ob_TowId
WHERE
dok_Status != 2 AND
datepart(wk, dok_DataWyst) BETWEEN datepart(wk, DATEADD(wk, -9, GETDATE())) AND datepart(wk, DATEADD(wk, -1, GETDATE()))
GROUP BY T.tw_Nazwa
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols =
ISNULL(@cols + ',','')
+ QUOTENAME(Tydzien)
FROM
(SELECT DISTINCT Tydzien FROM moja.dbo.tymczasowa) t
set @query = N'SELECT Nazwa,' + @cols + ' FROM moja.dbo.tymczasowa
PIVOT(
SUM(Suma)
FOR Tydzien IN ('+ @cols +')
) AS P
ORDER BY P.Nazwa'
EXECUTE sp_executesql @query
DROP TABLE nasza.dbo.tymczasowa