我有需要進行重構一個SQL查詢。基本上查詢獲取指定客戶訂購的所有產品類型。問題是結果是以列而不是行返回的。這需要改變另一種方式來使查詢更通用。重構SQL查詢返回的結果爲行,而不是列
原來這就是該查詢返回:
Name ProductType1 ProductType2 ProductType3
--------------------------------------------------
Marc PT09 P15 PT33
,這是它應該是什麼:
Name ProductType
----------------
Marc PT09
Marc P15
Marc PT33
這是我已經簡化了一下查詢:
SELECT
CustomerData.Name as Name
Product1.productType as ProductType1,
Product2.productType as ProductType2,
Product3.productType as ProductType3
FROM
(SELECT ProductID, Name
FROM
Customer
Orders
WHERE Customer.ID = 111
) as CustomerData
LEFT JOIN (SELECT DISTINCT CP.ProductID as ProductID,
PC.Type as ProductType
FROM
CustomerProduct CP,
ProductCategory PC
WHERE
PC.Category = 'A'
AND CP.ProductCategoryID = PC.ID
) as Product1
on CustomerData.ProductID = Product1.ProductID
LEFT JOIN (SELECT DISTINCT CP.ProductID as ProductID,
PC.Type as ProductType
FROM
CustomerProduct CP,
ProductCategory PC
WHERE
PC.Category = 'B'
AND CP.ProductCategoryID = PC.ID
) as Product2
on CustomerData.ProductID = Product1.ProductID
LEFT JOIN (SELECT DISTINCT CP.ProductID as ProductID,
PC.Type as ProductType
FROM
CustomerProduct CP,
ProductCategory PC
WHERE
PC.Category = 'C'
AND CP.ProductCategoryID = PC.ID
) as Product3
on CustomerData.ProductID = Product1.ProductID
所以我一直在想分裂加入到一個單獨的存儲過程,然後再調用這個,因爲我需要更多的productTypes,但我似乎無法得到這個工作。任何人有關如何使這項工作的想法?
在你面前已知產品類型的數量正在執行的查詢?如果是這樣,您可以動態創建具有多個UNION的SQL。 – 2011-03-17 10:55:20