在 SQL Server 2008 中按出现次数进行透视
我有如下数据:
我想将数据旋转为如下所示。每个尺寸最多有 3 个 oPack 值,我希望类别 + 类别 2 + 尺寸每个组合的所有 oPack 值在最后 3 列中按升序列出。
Category | Category2 | Size | Pack1 | Pack2 | Pack3
Chilled... Chilled 1.75-1.89L 1750 1890 NULL
Chilled... Chilled 1.75/1.89L 1750 1890 NULL
Chilled... Chilled 1.75L 1750 NULL NULL
Chilled... Chilled 1.89/2.63L 1890 2630 NULL
...
Chilled... Chilled 400-710mL 400 NULL NULL
我尝试过类似的东西:
select [Category],[Category2], [Pack1], [Pack2], [Pack3]
from (
select [Category],[Category2],[size], oPack
from myTable) p
pivot (Max(oPack) for oPack in ([Pack1], [Pack2], [Pack3])) as pvt
I have data like the following:
I want to pivot the data to look like this. There are a maximum of three oPack values per Size, and I'd like all the oPack values for each combination of Category + Category2 + Size to be listed in increasing order in the last 3 columns.
Category | Category2 | Size | Pack1 | Pack2 | Pack3
Chilled... Chilled 1.75-1.89L 1750 1890 NULL
Chilled... Chilled 1.75/1.89L 1750 1890 NULL
Chilled... Chilled 1.75L 1750 NULL NULL
Chilled... Chilled 1.89/2.63L 1890 2630 NULL
...
Chilled... Chilled 400-710mL 400 NULL NULL
I tried something like :
select [Category],[Category2], [Pack1], [Pack2], [Pack3]
from (
select [Category],[Category2],[size], oPack
from myTable) p
pivot (Max(oPack) for oPack in ([Pack1], [Pack2], [Pack3])) as pvt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

这正是您正在寻找的东西。首先,做一些餐桌准备。
然后,您的解决方案:
并且,可能有用的替代解决方案:
This gives exactly what you're looking for. First, a little table preparation.
Then, your solution:
And, an alternate solution that could be useful: