【问题标题】:Pivot SQL Server results by year按年份透视 SQL Server 结果
【发布时间】:2020-12-27 23:22:43
【问题描述】:

我不知道如何返回旋转结果。任何帮助是极大的赞赏。我的数据如下所示:

注意 SystemCategoryID 和 DataQualityCategoryID 3 有 2019 年的记录和 2020 年的记录。我需要像这样对结果进行透视:

因为 SystemCategoryID 和 DataQualityCategoryID 3 有 2020 年的记录,它将在与上一年相同的行中返回。因此,如果有多年的数据,则仅返回当前年份和上一年。这可能吗?

【问题讨论】:

  • 数据/T-SQL请不要使用图片,使用格式化文本。

标签: sql sql-server pivot pivot-table


【解决方案1】:

你可以像这样使用条件聚合:

select clientid, systemcategoryid, dataqualitycategoryid,
    max(case when year(datecaptured) = 2019 then datecaptured end) as datecaptured_2019,
    max(case when year(datecaptured) = 2019 then score        end) as score_2019
    max(case when year(datecaptured) = 2020 then datecaptured end) as datecaptured_2020,
    max(case when year(datecaptured) = 2019 then score        end) as score_2020
from mytable
where datecaptured >= '20190101' and datecaptured < '20210101'
group by month(datecaptured), day(datecaptured), clientid, systemcategoryid, dataqualitycategoryid

【讨论】:

    【解决方案2】:

    在我看来,这就像 left join

    select t2019.*, t2020.datecaptured, t2020.score
    from t t2019 left join
         t t2020
         on t2020.clientid = t2019.clientid and
            t2020.systemcategoryid = t2019.systemcategoryid and
            t2020.dataqualitycategoryid = t2019.dataqualitycategoryid and
            t2020.datecaptured = dateadd(year, 1, t2019.datecaptured)
    where t2019.datecaptured >= '2019-01-01' and
          t2019.datecaptured < '2020-01-01'
    

    【讨论】:

      猜你喜欢
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2023-04-08
      相关资源
      最近更新 更多