2016-02-23 78 views
1

我想從客戶表,合同支出表和合同名稱表中選擇數據。我的表是這個樣子dynamic pivot sql

Customers 
CustomerID CustomerName Address   etc 
1   "ABC Corp" "123 Here Ave" 
2   "Acme Corp" "101 Lets Ave" 

ContractTypes 
ContractTypeID ContractName 
1    "Website Hosting" 
2    "Domain Hosting" 
3    "Email Hosting" 

ServiceSpend 
ServiceSpendID ContractTypeID CustomerID Spend 
1    2    1   5.99 
2    1    1   5.99 
3    1    2   9.99 

我想下表產生

CustomerID CustomerName Address   DomainHosting WebsiteHosting 
1   "ABC Corp" "123 Here Ave" 9.99   5.99 

目前我有工作了下面的SQL語句,但我需要能夠動態地定義列,因爲我們需要能夠額外合約名稱添加到數據庫和客戶仍然報告花

select * 
from 
(
SELECT   
Customers.CustomerID, Customers.ContactName, Customers.Address,        ContractTypes.ContractName AS ContractName, ServiceSpend.Spend 
FROM    
Customers INNER JOIN 
ServiceSpend ON Customers.CustomerID = ServiceSpend.CustomerID 
INNER JOIN 
ContractTypes ON ServiceSpend.ContractTypeID = ContractTypes.ContractTypeID 
) src 
pivot 
(
sum(spend) 
    for ContractName in ([Website Hosting],[Domain Hosting])) piv; 

有誰知道我可以補充我的專欄dynami凱莉

+0

我不認爲你需要在這裏一個支點,爲什麼不只是做一組,並使用SUM來的總花場? – Chuck

+0

我該怎麼做?是否會爲我有的ContractNames列表創建列? – user1711657

+0

回想我的問題,我想我犯了一個錯誤,我想製作一個這樣的表格 '客戶ID,客戶名稱,地址,域名託管,網站託管 1,「ABC Corp」,「123 Here Ave」 ,9.99,5.99' – user1711657

回答

1

你必須使用動態SQL構造柱爲輸出:

DECLARE @Columns VARCHAR(1000) = STUFF((
    SELECT ',[' + ContactName + ']' 
    FROM ContactTypes 
    FOR XML PATH('') 
    ),1,1,'') 
DECLARE @Sql VARCHAR(1000) = ' 
    SELECT * 
    FROM (
     SELECT   
      Customers.CustomerID, 
      Customers.ContactName, 
      Customers.Address, 
      ContractTypes.ContractName, 
      ServiceSpend.Spend 
     FROM Customers 
      INNER JOIN ServiceSpend 
       ON Customers.CustomerID = ServiceSpend.CustomerID 
      INNER JOIN ContractTypes 
       ON ServiceSpend.ContractTypeID = ContractTypes.ContractTypeID 
     ) SRC 
     PIVOT (SUM(Spend) FOR ContractName IN (' + @Columns + ')) piv;' 
EXEC (@Sql) 
+0

** 1)**我個人更喜歡'STUFF(...,1,1,'')'去掉前面的逗號。 ** 2)**因爲該列沒有名稱,所以不需要設置「AS [text()]」列。 –

+0

好點...那是很久以前我被告知這麼做的方式,不知道爲什麼我沒有質疑它,因爲:)'STUFF'因爲很多原因而更好。感謝您的建議@TT –

+0

這很好,謝謝! – user1711657