我想從客戶表,合同支出表和合同名稱表中選擇數據。我的表是這個樣子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凱莉
我不認爲你需要在這裏一個支點,爲什麼不只是做一組,並使用SUM來的總花場? – Chuck
我該怎麼做?是否會爲我有的ContractNames列表創建列? – user1711657
回想我的問題,我想我犯了一個錯誤,我想製作一個這樣的表格 '客戶ID,客戶名稱,地址,域名託管,網站託管 1,「ABC Corp」,「123 Here Ave」 ,9.99,5.99' – user1711657