首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL转置?需要在一行中显示数量和价格,这在SQL中可能吗?

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

Stack Overflow用户
提问于 2014-04-17 15:01:05
回答 1查看 35关注 0票数 0

我有一个系统,在一个单独的表中存储产品的分层价格。现在,我被要求列出所有的产品与他们的层次价格在一排。我的分层价目表如下:

代码语言:javascript
复制
ProductId   Quantity    Price
----------- ----------- ---------------------------------------
12019       1           152.0208
12019       3           145.9375
12019       7           139.8542
12019       11          133.7710
12019       26          121.6044

我需要它看起来像这样:

代码语言:javascript
复制
ProductId   Qty1    Price1    Qty2  Price2    Qty3  Price3    ... Qty7  Price7
12019            1  152.0208  3 145.9375  7 139.8542
  • 我们有7种价格,但不是所有的产品都有,有些可能有4或6种。

您所能提供的任何建议都将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2014-04-18 11:50:09

嗯,我必须想出办法,也许不是最优雅的解决方案,但它是有效的!

我在发布我的解决方案,以防有人想要一个Pivot的替代方案,顺便说一句,我认为添加行计数字段要容易得多,请参见下面

首先,我在查询中添加了行计数,并在更改Id字段时将其重置:

代码语言:javascript
复制
select ProductId, 
ROW_NUMBER() 
        OVER (PARTITION BY ProductId ORDER BY ProductId) AS Row,

Quantity, Price from TierPriceTable

然后,我简单地为每个组中的每对写了一个查询:

代码语言:javascript
复制
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

我使用临时表来简化查询,但这是可选的。

我希望这能帮到你!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23136676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档