Group By动态列表与Count

时间:2014-10-03 19:57:28

标签: sql-server sql-server-2008

我使用简单的case语句计算我的数据中的breakcode的出现次数以及Seller和SaleDate的分组。

然而,这似乎是一个不优雅的解决方案。破解码可能并且很可能会扩展,我需要更新我的代码。怎么办呢?

此外,虽然使用NULL给我正确的答案,我想知道有没有更好的方法来计算我的breakcode实例,将0代替NULL返回错误的结果?

SELECT seller, 
saledate,
COUNT(CASE WHEN breakcode = 1 then 1 ELSE NULL END) as [Perfect],
COUNT(CASE WHEN breakcode = 2 then 1 ELSE NULL END) as [Simple],
COUNT(CASE WHEN breakcode = 3 then 1 ELSE NULL END) as [Medium],
COUNT(CASE WHEN breakcode = 4 then 1 ELSE NULL END) as [Dual1],
COUNT(CASE WHEN breakcode = 5 then 1 ELSE NULL END) as [Dual2],
COUNT(CASE WHEN breakcode = 6 then 1 ELSE NULL END) as [Hard],
COUNT(CASE WHEN breakcode = 7 then 1 ELSE NULL END) as [Difficult]
FROM test
GROUP BY seller, sale date

感谢。

SQLFiddle:http://sqlfiddle.com/#!3/26f6d/2

1 个答案:

答案 0 :(得分:2)

通过评论开发的最终版本:

DECLARE @sql AS NVARCHAR(MAX)
DECLARE @cols AS NVARCHAR(MAX)

SELECT @cols= ISNULL(@cols + ',','') + QUOTENAME(case when breakname like 'Perfect%' then 'Perfect' else breakname end)
FROM (select * from breaks where breakname not like 'Perfect - 90') a
group by id, breakname
order by id


SET @sql =
  N'SELECT seller, saledate, ' + @cols + '
    FROM (select seller, saledate, case when breakname like ''Perfect%'' then ''Perfect'' else breakname end breakname from test 
    inner join breaks on case when breakcode = 8 then 1 else breakcode end = id) derived
    PIVOT(count(breakname)
          FOR derived.breakname IN (' + @cols + ')) AS PVTTable
        ORDER BY seller, saledate'

EXEC sp_executesql @sql

SQL Fiddle