【问题标题】:Simplest "PIVOT" without Aggregation or Joins没有聚合或连接的最简单的“PIVOT”
【发布时间】:2019-10-15 19:01:19
【问题描述】:

我最基本的需求是将行“透视”到单独的列中,但经过一个小时的搜索后找不到简单的解决方案。

我的数据如下所示:

providernumber txnmy_cd
001            1234
001            4321
001            3214

我需要这样显示:

providernumber       txnmy_cd1, txnmy_cd2, txnmy_cd3
001                  1234       4321       3214

我尝试了几种方法,但我在这里看到的所有示例都具有聚合函数和/或连接,并且对于我正在尝试做的事情来说似乎有点矫枉过正。

【问题讨论】:

  • 对不起。 SQL/SQL Server 2008

标签: sql-server tsql pivot


【解决方案1】:

假设您不需要 DYNAMIC SQL

示例

Select *
 From  (
        Select [providernumber]
              ,Value = [txnmy_cd]
              ,Item = 'txnmy_cd'+ convert(varchar(25),row_number() over ( Partition By [providernumber] order by  (Select null) ) )
         From  YourTable
       ) src
 Pivot ( max(Value) for Item in ( [txnmy_cd1],[txnmy_cd2],[txnmy_cd3] ) ) pvt

退货

providernumber  txnmy_cd1   txnmy_cd2   txnmy_cd3
1               1234        4321        3214

【讨论】:

  • 谢谢约翰!查询效果很好,但我的 txnmy_cd1、txnmy_cd2 和 txnmy_cd3 列中的值都为 NULL。我错过了什么?
  • @user3406654 我不明白所有空值或分散?
  • 所有 NULLS...每个值都是空值。我可能只需要在某处写一个“ISNULL”来处理它们。 ???
  • 我的许多提供商没有分类代码,但我仍然需要列出它们。我希望这是有道理的。感谢您的帮助!
  • @user3406654 如果 ALL 为空,则其他错误。如果您确实有值,那么您可以使用 ISNULL 进行陷阱。 dbfiddle.uk/…
猜你喜欢
  • 2012-11-24
  • 2016-10-16
  • 2014-12-30
  • 1970-01-01
  • 2021-12-11
  • 2013-03-24
  • 2010-11-23
  • 2019-07-03
  • 2012-02-20
相关资源
最近更新 更多