SQL转置?需要在一行中显示数量和价格,这在SQL中是否可行?

SQL转置?需要在一行中显示数量和价格,这在SQL中是否可行?,sql,sql-server,Sql,Sql Server,我有一个系统,在一个单独的表中存储产品的分层价格。现在,我被要求在一行上列出所有产品及其分层价格。我的分层价格表如下所示: ProductId Quantity Price ----------- ----------- --------------------------------------- 12019 1 152.0208 12019 3 145.9375 12019 7 139.

我有一个系统,在一个单独的表中存储产品的分层价格。现在,我被要求在一行上列出所有产品及其分层价格。我的分层价格表如下所示:

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
我需要它看起来像这样:

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
  • 我们提高了7个价格,但不是所有的产品都有,有些可能有4或6个

如果您能提供任何建议,我们将不胜感激

好吧,我总得想个办法,也许不是最优雅的解决方案,但它很管用

我发布了我的解决方案,以防有人想要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
我使用临时表简化查询,但这是可选的


我希望这有帮助

感谢Gordon的正确格式化!谢谢Ryan,我搜索了论坛并从另一篇文章中获得了该链接,但该示例非常基本,仅针对一个专栏。我需要以两列为轴心,没有任何线索!是的,行数不同。但最大为7对(数量价格)