在SQL中动态创建列并用计数值填充它们,通常使用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>
动态列生成:
对于未知数量的列,可以使用动态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>
动态版本:
<code class="language-sql">DECLARE @cols AS NVARCHAR(MAX), @colsRollup 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,'') SELECT @colsRollup = STUFF((SELECT ', SUM(' + QUOTENAME(description) + ') AS '+ QUOTENAME(description) FROM customerrewards GROUP BY description, typeid ORDER BY typeid FOR XML PATH(''), TYPE ).VALUE('.', 'NVARCHAR(MAX)') ,1,1,'') SET @query = 'SELECT name, '+ @colsRollup + ' FROM ( 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 ) x1 GROUP BY name WITH ROLLUP' EXECUTE(@query)</code>
以上是如何使用 PIVOT 在 SQL 中动态生成和填充带有计数值的列?的详细内容。更多信息请关注PHP中文网其他相关文章!