【问题标题】:How to split columns based on field title如何根据字段标题拆分列
【发布时间】:2019-05-10 13:50:37
【问题描述】:

我正在使用单个仓库表,其中包含“2015 年费用”、“2015 年收入”、“2016 年费用”、“2016 年收入”等列。我需要将它们拆分为“收入”、“费用” ,和“开票年份”,以便做一些分析。许多记录都有多年的费用和收入。

我尝试的 CASE 语句仅在第一年中提取,但我需要它在所有年份中提取。

这是我的案例陈述:

    (CASE when 2015_revenue IS NOT NULL then 2015_revenue
        when 2016_revenue_$ IS NOT NULL then 2016_revenue
       END) as revenue,
(CASE when 2015_fee IS NOT NULL then 2015_fee
    when 2016_fee IS NOT NULL then 2016_fee
  END) as fee, 
(CASE when 2015_revenue IS NOT NULL then '2015'
        when 2015_fee IS NOT NULL then '2015'
        when 2016_revenue IS NOT NULL then '2016'
        when 2016_fee IS NOT NULL then '2016'
        end) as bill_year

有什么想法吗?

【问题讨论】:

  • 您将不得不写出这个 sql,因为架构不好。 ://
  • 您能否编辑您的问题,为输入数据提供一些示例行以及您希望从查询中获得的输出示例?然后我们将能够提供一些建议。

标签: sql amazon-redshift


【解决方案1】:

这不是 CASE 语句,它使用 UNION 创建一个临时表并加入:

    SELECT p1.[bunch of fields from table]
    amts.fee
    amts.revenue
    amts.bill_year
    FROM table p1
    JOIN (SELECT id, 2015_revenue as revenue, 2015_fee as fee, '2015' as bill_year FROM table
           UNION
           SELECT id, 2016_revenue as revenue, 2016_fee as fee, '2016' as bill_year FROM table
           U) amts on amts.id = p1.id;

【讨论】:

    猜你喜欢
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2011-12-19
    • 2014-03-27
    • 1970-01-01
    相关资源
    最近更新 更多