如何在 SQL 中添加类别列并通过在 SQL 中创建视图来调整记录大小

How to add a category column in SQL and resize the records by creating views in SQL

我需要创建 SQL 视图,它将当前 table 转换为下面提到的所需格式

我引入了一个新的类别列并相应地调整了列的形状。

当前 table 布局:

     Date  | A flows| B flows | C flows | A yield | B Yield | C Yield | A Spread |  B Spread |  C Spread
    ----------------------------------------------------------------------------------------------------
    1/1/17 |10      | 20      |30       |   5     |10       |15       | 1        |  2        |3   

所需的视图布局:

         Date   Category    flows   yield   Spread
         1/1/17     A       10       5       1
         1/1/17     B       20       10      2
         1/1/17     C       30       15      3

任何人都可以帮助创建一个 SQL 视图,它将现有列分为 3 个类别。

谢谢!

我会用 cross apply:

select v.*
from t cross apply
     (values (date, 'A', A_Flows, A_yield, A_spread),
             (date, 'B', B_Flows, B_yield, B_spread),
             (date, 'C', C_Flows, C_yield, C_spread)
      ) v(date, category, flows, yield, spread);

您可以在查询前添加 create view as 以创建视图。

您可以使用 UNION 来完成。 Select 将每个类别分开,然后将 3 个类别合并在一起:

SELECT Date, 'A' AS Category, A_flows AS flows, A_yield AS yield, A_spread AS spread FROM your_table
UNION
SELECT Date, 'B' AS Category, B_flows AS flows, B_yield AS yield, B_spread AS spread FROM your_table
UNION
SELECT Date, 'C' AS Category, C_flows AS flows, C_yield AS yield, C_spread AS spread FROM your_table