我有一个系统,在一个单独的表中存储产品的分层价格。现在,我被要求列出所有的产品与他们的层次价格在一排。我的分层价目表如下:
ProductId Quantity Price
----------- ----------- ---------------------------------------
12019 1 152.0208
12019 3 145.9375
12019 7 139.8542
12019 11 133.7710
12019 26 121.6044我需要它看起来像这样:
ProductId Qty1 Price1 Qty2 Price2 Qty3 Price3 ... Qty7 Price7
12019 1 152.0208 3 145.9375 7 139.8542您所能提供的任何建议都将不胜感激!
发布于 2014-04-18 11:50:09
嗯,我必须想出办法,也许不是最优雅的解决方案,但它是有效的!
我在发布我的解决方案,以防有人想要一个Pivot的替代方案,顺便说一句,我认为添加行计数字段要容易得多,请参见下面
首先,我在查询中添加了行计数,并在更改Id字段时将其重置:
select ProductId,
ROW_NUMBER()
OVER (PARTITION BY ProductId ORDER BY ProductId) AS Row,
Quantity, Price from TierPriceTable然后,我简单地为每个组中的每对写了一个查询:
select t.ProductID,
(select Qty from #prices where ProductID = t.ProductID and Row = 1) Qty1,
(select Price from #prices where ProductID = t.ProductID and Row = 1) Price1,
(select Qty from #prices where ProductID = t.ProductID and Row = 2) Qty2,
(select Price from #prices where ProductID = t.ProductID and Row = 2) Price2,
(select Qty from #prices where ProductID = t.ProductID and Row = 3) Qty3,
(select Price from #prices where ProductID = t.ProductID and Row = 3) Price3,
(select Qty from #prices where ProductID = t.ProductID and Row = 4) Qty4,
(select Price from #prices where ProductID = t.ProductID and Row = 4) Price4,
(select Qty from #prices where ProductID = t.ProductID and Row = 5) Qty5,
(select Price from #prices where ProductID = t.ProductID and Row = 5) Price5,
(select Qty from #prices where ProductID = t.ProductID and Row = 6) Qty6,
(select Price from #prices where ProductID = t.ProductID and Row = 6) Price6,
(select Qty from #prices where ProductID = t.ProductID and Row = 7) Qty7,
(select Price from #prices where ProductID = t.ProductID and Row = 7) Price7
from #prices t
group by t.ProductID我使用临时表来简化查询,但这是可选的。
我希望这能帮到你!
https://stackoverflow.com/questions/23136676
复制相似问题