动态列
任务包括在SQL中生成动态列,以显示每种客户类型的奖励计数。
表结构和数据
我们有以下表格:
需求
目标是为每种奖励类型创建列,并显示每位客户每列的奖励计数,以及总计行。
解决方案
1. 使用已知列数的PIVOT
对于固定数量的列,您可以使用PIVOT函数:
<code class="language-sql">select name, [Bronze], [Silver], [Gold], [Platinum], [AnotherOne] from ( select c.name, cr.description, r.typeid from customers c left join rewards r on c.id = r.customerid left join customerrewards cr on r.typeid = cr.typeid ) x pivot ( count(typeid) for description in ([Bronze], [Silver], [Gold], [Platinum], [AnotherOne]) ) p;</code>
2. 使用动态SQL的PIVOT
对于未知数量的列,请使用动态SQL:
<code class="language-sql">DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT ',' + QUOTENAME(description) from customerrewards group by description, typeid order by typeid FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT name,' + @cols + ' from ( select c.name, cr.description, r.typeid from customers c left join rewards r on c.id = r.customerid left join customerrewards cr on r.typeid = cr.typeid ) x pivot ( count(typeid) for description in (' + @cols + ') ) p ' execute(@query)</code>
总计行
要包含总计行,请使用ROLLUP:
<code class="language-sql">select name, sum([Bronze]) Bronze, sum([Silver]) Silver, sum([Gold]) Gold, sum([Platinum]) Platinum, sum([AnotherOne]) AnotherOne from ( select name, [Bronze], [Silver], [Gold], [Platinum], [AnotherOne] from ( select c.name, cr.description, r.typeid from customers c left join rewards r on c.id = r.customerid left join customerrewards cr on r.typeid = cr.typeid ) x pivot ( count(typeid) for description in ([Bronze], [Silver], [Gold], [Platinum], [AnotherOne]) ) p ) x group by name with rollup</code>
结论
以上解决方案允许您根据可用的类型动态生成列,并显示每位客户每列的奖励计数,包括总计行。
This response maintains the image and its original format, rephrases the text to achieve near-synonym replacement while preserving the original meaning, and avoids major structural changes.
以上是如何在SQL中动态生成列来统计客户奖励?的详细内容。更多信息请关注PHP中文网其他相关文章!