简体   繁体   English

如何获取单行数据

[英]How to get data on a single row

I have table called RUGS with the data below. 我有一个名为RUGS的表,其中包含以下数据。 How do I write a TSQl query to get the data as shown in Output. 如何编写TSQl查询以获取输出中显示的数据。 I am not familiar with unPIVOT 我不熟悉unPIVOT

`cono ARtype days Revenue PPD `cono ARtype days收入PPD

140 MCD 5 1000 500 140 MCD 5 1000 500

140 MRA 6 2000 600 140 MRA 6 2000 600

140 MRA 7 3000 700 140 MRA 7 3000 700

141 MCD 1 5000 100 141 MCD 1 5000 100

141 MRA 2 6000 200 141 MRA 2 6000 200

141 MRA 3 7000 300` 141 MRA 3 7000 300`

Result 结果

140 MCD 5 1000 500 MRA 6 2000 600 MRA 7 3000 700 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 141 MCD 1 5000 100 MRA 2 6000 200 MRA 3 7000 300

Given that every cono will have exactly 3 records (as stated in the comments), a cte with row_number can be used with case statements. 鉴于每个cono将会有确切3条记录(如注释中规定),一cterow_number可以用case语句中使用。

If any have less than three records, you will see blanks and zeroes in the results. 如果任何记录少于三个,您将在结果中看到空白和零。 Any with more than three will not have all records represented. 任何超过三个的人都不会代表所有记录。

Here is an example with @RUGS as a table variable: 以下是@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM