【问题标题】:How make from 4 variables only two in SQL?如何在 SQL 中从 4 个变量中仅生成两个变量?
【发布时间】:2021-03-28 22:31:15
【问题描述】:

我有下表

并希望达到以下结果

因此,group1 和 group 2 被分组到 GROUP,quantity1/2 到 QUANTITY。我尝试了交叉应用,但表格开始太大并且出现重复。

【问题讨论】:

    标签: sql sql-server unpivot lateral-join


    【解决方案1】:

    在 SQL Server 中,我会推荐 cross apply 取消透视:

    select t.date, t.fund, x.*
    from mytable t
    cross apply (values (t.group1, t.quantity1), (t.group2, t.quantity2)) as x(grp, qty)
    

    横向连接是一种强大的工具。这比union all 更高效,因为该表只被扫描一次。

    【讨论】:

      【解决方案2】:

      您可以应用UNION 操作,如下:

      SELECT date, fund, group1 as grp, quantity1 as quantity
      FROM yourtable
      UNION ALL
      SELECT date, fund, group2, quantity2
      FROM yourtable
      

      我使用了UNION ALL,因为你的 group1 和 group2 总是不同的(作为你的数据样本),所以你不应用 ALL,distinct 操作。

      【讨论】:

      • 你不需要别名 group2 和 quantity2 吗?
      • @T.Peter:不,亲爱的,别名在第一个查询中是可以的。其他以位置方式进行
      • tbh 我从来不知道这一点,所以该列的其余部分将按位置自动合并?谢谢你的信息。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 2017-02-20
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多