【问题标题】:SQL Pivot on Int for String [closed]SQL Pivot on Int for String [关闭]
【发布时间】:2014-12-19 15:45:16
【问题描述】:

尝试使用 Pivot 操作一些 SQL,但是我需要以文本为中心,但我不能让它正常工作。

customerID  appointment             appointmentNumber   treatment
9           2014-01-09 09:30:00.000 1                   Osteo F 45
9           2014-01-20 09:00:00.000 2                   Osteo F 45
9           2014-01-30 09:30:00.000 3                   Osteo F 45
9           2014-02-10 09:00:00.000 4                   Osteo F 45

我需要将“appointmentNumber”列变成列标题,下面显示“治疗”...

customerID 1 2 3 4 etc...

过去,我一直在字符串上使用数据透视表来表示数字(总和、计数),而从来没有在字符串上使用数据透视表,所以我有点迷茫。

我查看了SQL Pivot with String,但似乎无法将其应用于我自己的代码。

有什么想法吗?

【问题讨论】:

  • 向我们展示您尝试过的代码以及出现错误的位置。
  • 你尝试过使用 first() 函数吗?

标签: sql string tsql pivot


【解决方案1】:

您可以为字符串列选择最大/最小聚合函数。在这种情况下,我假设 AppointmentNumber、customerId 是唯一的,因此聚合函数除了获取第一个值之外并没有真正做任何事情。

select
    *
from
    table t
    pivot (
        max(treatment)
        for appointmentNumber in ([1],[2],[3],[4],[5])
    ) p

【讨论】:

    【解决方案2】:

    您可以通过max() 使用条件聚合:

    select customerId,
           max(case when appointmentnumber = 1 then treatement end) as an_1,
           max(case when appointmentnumber = 2 then treatement end) as an_2,
           max(case when appointmentnumber = 3 then treatement end) as an_3,
           max(case when appointmentnumber = 4 then treatement end) as an_4,
           max(case when appointmentnumber = 5 then treatement end) as an_5
    from table t
    group by customerid;
    

    如果您愿意,您也可以使用pivot 执行此操作。 max() 适用于字符串变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-06
      • 2021-02-03
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多