Предоставление решения для MS-SQL Server -
Создание таблиц и данных -
CREATE TABLE [dbo].[Type](
[daynumbers] [date] NULL,
[daystotal] [int] NULL,
[types] [varchar](15) NULL,
[percount] [float] NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Type]
([daynumbers]
,[daystotal]
,[types]
,[percount])
VALUES
('2018-04-16', 5 ,'166su01', 60)
,('2018-04-16', 7 ,'166su02', 28.57)
,('2018-04-18', 8 ,'166su02', 62.5)
,('2018-04-19', 5 ,'166su01', 100)
Проблема состоит из двух частей -
- Выполнениенесколько сводок (один для percount и один для daystotal) из одного столбцаn (типы)
- Создание запроса, применимого к динамическому sql
Часть 1 -
Thisможет быть решен путем дублирования столбца типов и присвоения ему имени types1 и двойного поворота таблицы - один для percount и один для daystotal
SELECT *
FROM
(SELECT *,types+' Count'[types1] FROM dbo.Type) AS SourceTable --duplicate column created here
PIVOT
(
SUM(percount)
FOR types IN ([166su01], [166su02])
) AS PivotTable
PIVOT
(
SUM(daystotal)
FOR types1 IN ([166su01 Count], [166su02 Count])
) AS PivotTable
Это создаст дополнительные строки. Таким образом, для группировки их с использованием столбца daynumbers следующим образом-
SELECT daynumbers,Sum([166su01])[166su01],Sum( [166su01 Count]) [166su01 Count], Sum([166su02])[166su02],Sum( [166su02 Count]) [166su02 Count] FROM
(SELECT *,types+' Count'[types1] FROM dbo.Type) AS SourceTable
PIVOT
(
SUM(percount)
FOR types IN ([166su01], [166su02])
) AS PivotTable
PIVOT
(
SUM(daystotal)
FOR types1 IN ([166su01 Count], [166su02 Count])
) AS PivotTable
group by
daynumbers
Часть 2. Создание динамического запроса Необходимо динамически определить следующие элементы -
- Заголовки выбранного запроса - Сумма ([166su01]) [166su01], Сумма([166su01 Count]) [166su01 Count], Sum ([166su02]) [166su02], Sum ([166su02 Count]) [166su02 Count]
- Percount Pivot - [166su01], [166su02]
- DaysTotal Pivot - [166su01 Count], [166su02 Count]
Это можно сделать с помощью -
DECLARE @PivotPercount NVARCHAR(MAX) = N'' --Variable to hold types to pivot for percount
SELECT @PivotPercount = @PivotPercount + ', [' + COALESCE(types, '') + ']' FROM (SELECT DISTINCT types FROM dbo.Type)DT
SELECT @PivotPercount = LTRIM(STUFF(@PivotPercount, 1, 1, '')) --Remove first comma and space
print @PivotPercount
DECLARE @PivotDaysTotal NVARCHAR(MAX) = N'' --Variable to hold types to pivot for daystotal
SELECT @PivotDaysTotal = @PivotDaysTotal + ', [' + COALESCE(types, '') + ' Count]' FROM (SELECT DISTINCT types FROM dbo.Type)DT
SELECT @PivotDaysTotal = LTRIM(STUFF(@PivotDaysTotal, 1, 1, '')) --Remove first comma and space
print @PivotDaysTotal
DECLARE @Headers NVARCHAR(MAX) = N'' --Variable to hold unique customers to be used in PIVOT clause
SELECT @Headers = @Headers + ', Sum([' + COALESCE(types, '') + '])'+'[' + COALESCE(types, '') + ']' + ',Sum( [' + COALESCE(types, '') + ' Count]) ' + '[' + COALESCE(types, '') + ' Count]' FROM (SELECT DISTINCT types FROM dbo.Type)DT
SELECT @Headers = LTRIM(STUFF(@Headers, 1, 1, '')) --Remove first comma and space
print @Headers
Теперь все объединяется - Окончательный запрос -
DECLARE @PivotPercount NVARCHAR(MAX) = N'' --Variable to hold types to pivot for percount
SELECT @PivotPercount = @PivotPercount + ', [' + COALESCE(types, '') + ']' FROM (SELECT DISTINCT types FROM dbo.Type)DT
SELECT @PivotPercount = LTRIM(STUFF(@PivotPercount, 1, 1, '')) --Remove first comma and space
print @PivotPercount
DECLARE @PivotDaysTotal NVARCHAR(MAX) = N'' --Variable to hold types to pivot for daystotal
SELECT @PivotDaysTotal = @PivotDaysTotal + ', [' + COALESCE(types, '') + ' Count]' FROM (SELECT DISTINCT types FROM dbo.Type)DT
SELECT @PivotDaysTotal = LTRIM(STUFF(@PivotDaysTotal, 1, 1, '')) --Remove first comma and space
print @PivotDaysTotal
DECLARE @Headers NVARCHAR(MAX) = N'' --Variable to hold unique customers to be used in PIVOT clause
SELECT @Headers = @Headers + ', Sum([' + COALESCE(types, '') + '])'+'[' + COALESCE(types, '') + ']' + ',Sum( [' + COALESCE(types, '') + ' Count]) ' + '[' + COALESCE(types, '') + ' Count]' FROM (SELECT DISTINCT types FROM dbo.Type)DT
SELECT @Headers = LTRIM(STUFF(@Headers, 1, 1, '')) --Remove first comma and space
print @Headers
DECLARE @SQLStatement NVARCHAR(MAX) = N'' --Variable to hold t-sql query
--Generate dynamic PIVOT query here
SET @SQLStatement =
N'SELECT daynumbers,' + @Headers +
' FROM
(SELECT *,types+'' Count''[types1] FROM dbo.Type) AS SourceTable
PIVOT
(
SUM(percount)
FOR types IN ('+ @PivotPercount +')
) AS PivotTable
PIVOT
(
SUM(daystotal)
FOR types1 IN (' + @PivotDaysTotal + ')
) AS PivotTable
group by
daynumbers
'
print @SQLStatement
--Execute the dynamic t-sql PIVOT query below
EXEC (@SQLStatement)
Пожалуйста, проголосуйте за ответ, если он окажется полезным