计算Dynamic Pivot Sql中的子总计和总计

时间:2017-06-23 04:25:27

标签: sql sql-server pivot

我尝试在动态数据透视中创建一个包含总计和子总数的查询。

我有一个有3列的表:
enter image description here

如何获得这样的结果?

enter image description here

这是我的查询,但我无法创建总计和子总数:

DECLARE @Columns as VARCHAR(MAX)

SELECT @Columns =
COALESCE(@Columns + ', ','') + QUOTENAME(item)
from @mytable

DECLARE @SQL as VARCHAR(MAX)
SET @SQL = 
'SELECT name, location, ' + @Columns + '
FROM
(
    SELECT name, location, item
    FROM @mytable

) as PivotData
PIVOT
(
    count(item)
    for item  IN (' + @Columns + ')
) AS PivotResult
'

EXEC(@SQL)

感谢您的帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

您可以使用GROUP BY GROUPING SETSTotal item

之前计算Pivot
CREATE TABLE #SampleData
(
    Name varchar(10),
    Location varchar(20),
    Item varchar(10)
)

INSERT INTO #SampleData
VALUES
('Ron', 'Loc A', 'Pencil'),
('Ron', 'Loc A', 'Pencil'),
('Ron', 'Loc B', 'Pen'),
('Ron', 'Loc B', 'Laptop'),
('Tom', 'Loc A', 'Pencil'),
('Tom', 'Loc B', 'Pencil'),
('Tom', 'Loc B', 'Pen'),
('Tom', 'Loc A', 'Pencil'),
('Tom', 'Loc A', 'Laptop'),
('Tom', 'Loc A', 'Pencil')


DECLARE @Columns as VARCHAR(MAX)

SELECT @Columns =
COALESCE(@Columns + ', ','') + QUOTENAME(sd.item)
from (select DISTINCT item from #SampleData) sd

DECLARE @SQL as VARCHAR(MAX)
SET @SQL = 
'SELECT name, location, ' + @Columns + '
FROM
(
    SELECT  CASE WHEN sd.Location is null then ''Total '' + sd.Name
             ELSE sd.Name
          END as Name, 
          sd.Name as GroupName,
          sd.Location, sd.item, count(item) AS CountValue
    FROM #SampleData sd
    GROUP BY GROUPING SETS ((sd.Name, sd.Location, sd.item),(sd.Name, sd.item))

) as PivotData
PIVOT
(
    sum(CountValue)
    for item  IN (' + @Columns + ')
) AS PivotResult
Order by GroupName, name
'

EXEC(@SQL)

DROP TABLE #SampleData

演示链接:http://rextester.com/GTKM34090

答案 1 :(得分:1)

使用<DataGrid.RowValidationRules> <local:CourseValidationRule ValidationStep="UpdatedValue"/> </DataGrid.RowValidationRules> ROLLUP

执行此操作的另一种方法
GROUPING

注意:我对如何将行连接成逗号分隔值进行了更改。您当前的字符串连接方法并不能保证始终有效。我使用DECLARE @Pivot_Columns AS VARCHAR(MAX), @select_Columns VARCHAR(max) SELECT @Pivot_Columns = Stuff((SELECT DISTINCT ',' + Quotename(item) FROM #SampleData FOR xml path('')), 1, 1, '') SELECT @select_Columns = Stuff((SELECT DISTINCT ',Sum(' + Quotename(item) + ') as '+Quotename(item) FROM #SampleData FOR xml path('')), 1, 1, '') DECLARE @SQL AS VARCHAR(MAX) SET @SQL = 'SELECT case when grouping(location) = 1 and grouping(name) = 0 then ''Total''+ '' '' + name when grouping(location) = 1 and grouping(name) = 1 then ''Total'' else name end Name, location, ' + @select_Columns + ' FROM ( SELECT name, location, item FROM #SampleData ) as PivotData PIVOT ( count(item) for item IN (' + @Pivot_Columns + ') ) AS PivotResult group by name,location with rollup ' EXEC(@SQL) 方法进行连接。