我有需要进行重构一个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