如何订购枢轴?

时间:2017-07-04 09:20:36

标签: sql sql-server pivot

这个问题与我之前的问题类似,但我不知道找到解决方案,因为我不使用联合。

我有这个查询

private FinderPattern[] selectBestPatterns()
    {
        int startSize = possibleCenters.Count;
        if (startSize < 3)
        {
            // Couldn't find enough finder patterns
            return null; // It returns here
        }
        ...

结果如下:

enter image description here

如何订购我的查询看起来像这样?如果没有我的位置计数我的查询工作正常

enter image description here

我需要解决方案来解决这个问题,提前谢谢!!

1 个答案:

答案 0 :(得分:0)

这种输出是否可以接受?

Name             Location             Laptop      Pen         Pencil
---------------- -------------------- ----------- ----------- -----------
Ron              Loc A                0           0           2
Ron              Loc B                1           1           0
Ron Total        2                    1           1           2
Tom              Loc B                0           1           1
Tom              Loc A                1           0           3
Tom Total        2                    1           1           4
Total            2                    2           2           6

我使用的查询:

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 name + '' ''+ ''Total''
when grouping(location) = 1 and grouping(name) = 1 then ''Total'' 
else name end Name, 
case when grouping(location) = 1 and grouping(name) = 0 then CONVERT(varchar(10), COUNT(Distinct location ))
when grouping(location) = 1 and grouping(name) = 1 then CONVERT(varchar(10), COUNT(Distinct location ))
else Location end 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 
ORDER BY GROUPING (name), name'

EXEC(@SQL)