請問各位大大
如已寫一段T-SQL (程式碼如下)
SELECT顯示如圖右
希望能顯示成如圖左的話
該用甚麼語法修改
感激不盡
SELECT 公司 ,
ISNULL(CAST(SUM(CASE WHEN 類別 LIKE 'A%' THEN 銷售金額 END) AS VARCHAR),'') AS 'A類' ,
ISNULL(CAST(SUM(CASE WHEN 類別 LIKE 'B%' THEN 銷售金額 END) AS VARCHAR),'') AS 'B類' ,
ISNULL(CAST(SUM(CASE WHEN 類別 LIKE 'C%' THEN 銷售金額 END) AS VARCHAR),'') AS 'C類'
FROM 銷售檔
如果用的是SQL Server 2005以後的版本,可以使用PIVOT加上動態組成欄位的技巧
<pre class="c" name="code">
SELECT [公司],('類別' + [類別]) AS [類別],[銷售金額] INTO #tmp FROM [tb1]
GO
DECLARE @ColHeader VARCHAR(MAX)
DECLARE @SQL NVARCHAR(MAX)
SELECT @ColHeader =
COALESCE(
@ColHeader + ',[' + CAST([類別] AS varchar) + ']',
'[' + CAST([類別] AS varchar) + ']'
)
FROM (SELECT DISTINCT [類別] FROM #tmp) AS x
SET @SQL = N'
SELECT * FROM #tmp PIVOT (SUM([銷售金額]) FOR [類別] IN (' + @ColHeader + ')) AS p'
EXECUTE(@SQL)
DROP TABLE #tmp