【问题标题】:How to get data on a single row如何获取单行数据
【发布时间】:2014-02-20 18:36:12
【问题描述】:

我有一个名为 RUGS 的表格,其中包含以下数据。如何编写 TSQl 查询以获取输出中所示的数据。我不熟悉 unPIVOT

`cono ARtype days 收入 PPD

140 MCD 5 1000 500

140 MRA 6 2000 600

140 MRA 7 3000 700

141 MCD 1 5000 100

141 MRA 2 6000 200

141 MRA 3 7000 300`

结果

140 MCD 5 1000 500 MRA 6 2000 600 MRA 7 3000 700

141 MCD 1 5000 100 MRA 2 6000 200 MRA 3 7000 300

【问题讨论】:

  • 你如何决定列的顺序?每个ID总是有3条记录吗?如果多或少怎么办?
  • 是的 - 非常 cono 的 3 条记录。对于 3 条记录,cono 应该只出现一次。
  • 你在stackoverflow.com/questions/21890782/…之前问过同样的问题,请不要重复同样的问题
  • 那是水晶报表中的。现在我需要一个 Tsql 查询

标签: tsql


【解决方案1】:

鉴于每个 cono 将有 3 条记录(如 cmets 中所述),cterow_number 可以与 case 语句一起使用。

如果任何记录少于三个,您将在结果中看到空白和零。超过三个的任何记录都不会代表所有记录。

这是一个使用@RUGS 作为表变量的示例:

declare @RUGS table (cono int, ARType char(3), [days] int, Revenue int, PPD int)

insert into @RUGS VALUES
(140,'MCD',5,1000,500)
,(140,'MRA',6,2000,600)
,(140,'MRA',7,3000,700)
,(141,'MCD',1,5000,100)
,(141,'MRA',2,6000,200)
,(141,'MRA',3,7000,300);

with cte as 
(
    select row_number() over(partition by cono order by (select 1)) as rn, * from @RUGS
)

select cono, 
    max(case when rn = 1 then ARType else '' end) as ARType1, 
    max(case when rn = 1 then days else '' end) as days1, 
    max(case when rn = 1 then Revenue else '' end) as Revenue1, 
    max(case when rn = 1 then PPD else '' end) as PPD1,
    max(case when rn = 2 then ARType else '' end) as ARType2, 
    max(case when rn = 2 then days else '' end) as days2, 
    max(case when rn = 2 then Revenue else '' end) as Revenue2, 
    max(case when rn = 2 then PPD else '' end) as PPD2,
    max(case when rn = 3 then ARType else '' end) as ARType3, 
    max(case when rn = 3 then days else '' end) as days3, 
    max(case when rn = 3 then Revenue else '' end) as Revenue3, 
    max(case when rn = 3 then PPD else '' end) as PPD3      
from cte group by cono

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2022-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2019-12-31
    • 2019-08-29
    相关资源
    最近更新 更多