在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中文網其他相關文章!