在 SQL Server 2008 中将行转换为列
我们有一张名为许可证的表。它看起来像这样:
CustNum | LicenseAddress | License | ExpiryDate |
---|---|---|---|
155 | 123 | Y32CA | 12/31/2018 |
155 | 998 | Y32CB | 12/31/2020 |
155 | 568 | Y32CC | 12/31/2022 |
这是我想要的样子:
LicAddr1 | Lic1 | ExpiryDate1 | LicAddr2 | Lic2 | ExpiryDate2 | LicAddr3 | Lic3 | ExpiryDate3 |
---|---|---|---|---|---|---|---|---|
123 | Y32CA | 12/31/2018 | 998 | Y32CB | 12/31/2020 | 568 | Y32CC | 12/31/2022 |
这是我当前的查询,但它只返回 NULL:
SELECT LicAddr1,
Lic1,
ExpiryDate1,
LicAddr2,
Lic2,
ExpiryDate2,
LicAddr3,
Lic3,
ExpiryDate3
FROM (SELECT CustNum, LicenseAddress, License, ExpiryDate FROM Licenses) d
PIVOT (
MAX(ExpiryDate)
FOR CustNum IN (LicAddr1, Lic1, ExpiryDate1, LicAddr2, Lic2, ExpiryDate2, LicAddr3, Lic3, ExpiryDate3)
) piv
我做错了什么?
We have one table called Licenses. This is what it looks like:
CustNum | LicenseAddress | License | ExpiryDate |
---|---|---|---|
155 | 123 | Y32CA | 12/31/2018 |
155 | 998 | Y32CB | 12/31/2020 |
155 | 568 | Y32CC | 12/31/2022 |
Here is what I want it to look like:
LicAddr1 | Lic1 | ExpiryDate1 | LicAddr2 | Lic2 | ExpiryDate2 | LicAddr3 | Lic3 | ExpiryDate3 |
---|---|---|---|---|---|---|---|---|
123 | Y32CA | 12/31/2018 | 998 | Y32CB | 12/31/2020 | 568 | Y32CC | 12/31/2022 |
Here is the query I have currently, however it’s only returning NULLs:
SELECT LicAddr1,
Lic1,
ExpiryDate1,
LicAddr2,
Lic2,
ExpiryDate2,
LicAddr3,
Lic3,
ExpiryDate3
FROM (SELECT CustNum, LicenseAddress, License, ExpiryDate FROM Licenses) d
PIVOT (
MAX(ExpiryDate)
FOR CustNum IN (LicAddr1, Lic1, ExpiryDate1, LicAddr2, Lic2, ExpiryDate2, LicAddr3, Lic3, ExpiryDate3)
) piv
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PIVOT
并不是您真正想要的,特别是因为您试图从每一行获取多个值(这与聚合PIVOT
配合得不太好)尝试提供)。我假设您需要最近的三个许可证,在这种情况下,我们可以为每个
CustNum
应用一个行号,按ExpiryDate
排序(最新的在前),然后翻转它们所以它们是从左到右从最旧到最新:结果:
PIVOT
isn't really what you're after, especially since you're trying to get multiple values from each row (which doesn't work very well with the aggregationPIVOT
tries to offer).I'm assuming here you want the most recent three licenses, in which case we can apply a row number per
CustNum
, ordered byExpiryDate
(newest first), then flip them so they are left-to-right oldest-to-newest:Results: