【问题标题】:SQL Server pivot code help needed需要 SQL Server 数据透视代码帮助
【发布时间】:2017-04-26 08:52:22
【问题描述】:

我希望从此查询中转换一些数据

select 
    count(*) as total_customers,
    sum(last_year) as customers_in_last_year
    sum(two_years) as customers_in_last_2_years
from
    Customers

返回这个结果集:

total_customers    customers_in_last_year    customers_in_last_2_years
500                  100                         200

我想做的就是把它翻到下面,有什么帮助吗?

total_customers                500
customers_in_last_year         100
customers_in_last_2_years      200

谢谢

【问题讨论】:

    标签: sql-server pivot unpivot


    【解决方案1】:

    假设您将结果存储到名为YourResult 的表中(可以是临时表、变量表),您可以执行以下操作:

    select 'total_customers' as col, total_customers as val from YourResult
    union all
    select 'customers_in_last_year' as col, customers_in_last_year as val from YourResult
    union all
    select 'customers_in_last_2_years' as col, customers_in_last_2_years as val from YourResult
    

    检查一个工作示例here

    【讨论】:

      【解决方案2】:
      CREATE TABLE #Table11
          ([total_customers] int, [customers_in_last_year] int, [customers_in_last_2_years] int)
      ;
      
      INSERT INTO #Table11
          ([total_customers], [customers_in_last_year], [customers_in_last_2_years])
      VALUES
          (500, 100, 200)
      
      
      select [subject],total_customerss as  total_customers
      from #Table11 s
      unpivot
      (
        total_customerss  
        for subject in ([total_customers], [customers_in_last_year], [customers_in_last_2_years])
      ) u;
      

      输出

      total_customers               500
      customers_in_last_year        100
      customers_in_last_2_years     200
      

      像这样附加您的查询

      SELECT [subject]
          ,total_customerss AS total_customers
      FROM (
          SELECT count(*) AS total_customers
              ,sum(last_year) AS customers_in_last_year, sum(two_years) AS customers_in_last_2_years
          FROM Customers
          ) s
      unpivot(total_customerss FOR subject IN (
                  [total_customers]
                  ,[customers_in_last_year]
                  ,[customers_in_last_2_years]
                  )) u;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-17
        • 1970-01-01
        • 1970-01-01
        • 2014-03-02
        • 2017-09-28
        相关资源
        最近更新 更多