【问题标题】:SQL Server daily report multiple columns to rowsSQL Server 每日报告多列到行
【发布时间】:2022-01-17 22:42:02
【问题描述】:

我有一张这样的桌子:

create table t_daily_total(
                Id          bigint identity not null,
                ReportDay   date null,
                Value1      decimal(10,2)  default 0 null,
                Value2      decimal(10,2) default 0 null
            ...
                Valuen      decimal(10,2) default 0 null
            )

我想以如下格式查看它:

ValueName, [2021-01-01],[2021-01-02], .... [2021-05-05]
Value1,    1, 2, 3.....
Value2, 5, 6, 7...
....
Valuen, 8, 9 10...

基本上按天查看值。我正在使用 SQL Server 2014。我检查了数据透视和取消数据透视,但仍然无法使其工作。请帮忙。谢谢!

【问题讨论】:

  • 请在 PIVOT 尝试更新您的问题。还包括一些示例数据。
  • 看来您应该修复您的设计。没有很多 Value 列,有 2 列(类似于 ValueValueNumber),然后每个值 1 行。规范化您的数据将使您的查询变得更加容易。
  • 数据看起来像:``` 插入到 t_daily_total(ReportDay, Value1, Value2, Value3.. Valuen) 值 ('2021-01-01',1, 2, 3.. .n), ('2021-01-02',1, 2, 3...n)。 ```如果将列名从value1...valuen更改为field1,field2,fieldn可能很容易理解,有意义吗?
  • @lptr 这正是我所需要的。效果很好,非常感谢!!
  • 更正 [在 string_agg() 中将 reportdays 转换为 nvarchar(max)].. 并且顺序仅用于演示 (char value10dbfiddle.uk/…

标签: sql-server pivot unpivot


【解决方案1】:

我是这样工作的:

[![--- table structure
create table t_daily_grand_total(
    Id          bigint identity not null,
    ReportDay   date null,
    ValueName   varchar(10) null,
    Value       decimal(10,2) default 0 null
    primary key(Id)
)

-- init data
declare @i int = 0
declare @d date = '2021-01-01'
while @i < 50
begin
    insert into t_daily_grand_total(ReportDay, ValueName, Value)  values
        (@d, 'v1',floor(rand()*60) + 20),
        (@d, 'v2',floor(rand()*60) + 20),
        (@d, 'v3',floor(rand()*60) + 20)
    set @i = @i + 1
    set @d = dateadd(day,1 , @d)
end

-- source data
select * from t_daily_grand_total

-- the final result
select * from
(select ReportDay, ValueName, Value from t_daily_grand_total) as st
pivot(
        sum(Value)
        for ReportDay in(\[2021-01-01\],\[2021-01-02\], \[2021-01-04\], \[2021-01-07\])
    ) as pt][1]][1]

【讨论】:

  • 现在只需要使列动态化,这很容易
猜你喜欢
  • 1970-01-01
  • 2013-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多