【问题标题】:simple(?) PIVOT without an aggregate没有聚合的简单(?)PIVOT
【发布时间】:2012-11-24 21:33:30
【问题描述】:

枢轴,伙计……我只是想念它。也许是因为我没有做聚合。哎呀,也许枢轴不是做到这一点的方法。感觉应该很简单,但它让我很难过。

假设我有这个:

SELECT col1
FROM tbl1

col1
====
414
589

我怎样才能得到这两条记录:

fauxfield1  fauxfield2
==========  ==========
414         589

针对这个问题的一些注意事项

  • 永远不会取回超过两条记录
  • 我总是要取回整数,但我不知道它们会是什么

【问题讨论】:

    标签: sql sql-server tsql pivot


    【解决方案1】:

    如果你有两个值,你可以这样做

    select
        (select top(1) col1 from tbl1 order by col1) fauxfield1,
        (select top(1) col1 from tbl1 order by col1 desc) fauxfield2;
    

    但我不明白为什么需要避免聚合?你有没有发现 SQL Server 的一些残缺版本?正常的查询是

    select min(col1) fauxfield1, max(col1) fauxfield2
      from tbl1;
    

    【讨论】:

      【解决方案2】:

      您可以实现PIVOT 运算符:

      select [1] as field1,
        [2] as field2
      from
      (
        select col1, row_number() Over(order by col1) rn
        from yourtable
      ) src
      pivot
      (
        max(col1)
        for rn in ([1], [2])
      ) piv
      

      SQL Fiddle with Demo

      【讨论】:

      • 纯金!花了我一点时间来弄清楚你在用 row_number 做什么。非常感谢!
      • 跟进 - 如果没有排名函数(如 row_number),我如何在 SQL 2000 中执行此操作?
      • 您使用的是 SQL Server 2000 吗?如果是这样,则没有 PIVOT 函数或像 row_number() 这样的窗口函数,您将不得不使用其他答案之一来获得结果。
      【解决方案3】:

      如果你知道你只得到两个,为什么不这样做:

      SELECT 
          MIN(col1) ff1
          , CASE MAX(col1) 
              WHEN MIN(col1) THEN NULL
              ELSE MAX(col1)
            END ff2
      FROM 
          tbl1;
      

      如果有两个值,这只会显示第二个值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-16
        • 2014-12-30
        • 1970-01-01
        • 2013-03-24
        • 2010-11-23
        • 2019-07-03
        • 2012-02-20
        • 1970-01-01
        相关资源
        最近更新 更多