[英]How to get data of a table filled from a text file with csv format in sql server
This is the data I get from the bulk import and I have in a table called Drinks:这是我从批量导入中获得的数据,我在名为 Drinks 的表中有:
| Descrip | 10/02/20 07 | 17/02/20 08 | 24/02/20 09 |
| SL AGUA | NULL | NULL | 2.861 |
| ALHAMBRA IPA | 350 | NULL | NULL |
| Carlsberg | 800 | 2.800 | 2.800 |
| CASIMIRO MH | NULL | 55 | NULL |
I need to do a query to obtain the data like this:我需要做一个查询来获取这样的数据:
| SL AGUA | 20 | 09 | 2861 |
| ALHAMBRA IPA | 20 | 07 | 350 |
| Carlsberg | 20 | 07 | 800 |
| Carlsberg | 20 | 08 | 2800 |
| Carlsberg | 20 | 09 | 2800 |
| CASIMIRO MH | 20 | 08 | 55 |
The first row has data like header (Descrip) but has also data I need like date and number of the week.第一行有像标题(描述)这样的数据,但也有我需要的数据,比如日期和星期几。
Is it possible to do what I need?可以做我需要的吗? Thanks.谢谢。
Load the data into a staging table, with columns from the first row.将数据加载到临时表中,列来自第一行。
Then unpivot, I would recommend using apply
:然后unpivot,我建议使用apply
:
select s.descrip, v.col1, vol2, v.val
from staging s cross apply
(values ([10/02/20 07], 20, 7),
([10/02/20 08], 20, 8),
([10/02/20 09], 20, 9)
) v(val, col1, col2)
where v.val is not null; -- or perhaps v.val <> ''
Follow the below step:请按照以下步骤操作:
create table Drinks
(
Head1 nvarchar(100),
Head2 nvarchar(100),
Head3 nvarchar(100),
Head4 nvarchar(100)
)
insert into Drinks values('Descrip','10/02/20 07','17/02/20 08','24/02/20 09'),
('SL AGUA',NULL,NULL,'2.861'),
('ALHAMBRA IPA','350',NULL, NULL),
('Carlsberg','800','2.800','2.800'),
('CASIMIRO MH',NULL,'55',NULL)
;with tempCTE
as (
select head1,head2,head3,head4,
head5=(case when head2 is not null then head5 else '' end) ,
head6=(case when head3 is not null then head6 else '' end) ,
head7=(case when head4 is not null then head7 else '' end)
from Drinks
cross apply (
select
head5=right(Head2,2) + '|' + substring(Head2,7,2),
head6=right(Head3,2)+'|'+substring(Head3,7,2),
head7=right(Head4,2)+'|'+substring(Head4,7,2)
from Drinks
where head1='Descrip'
) as tbl
cross apply (
select 1 slno union select 2
) as tbl2
where head1<>'Descrip'
), resultCTE
as
(
select distinct head1,SplitHead1=left(head5,2),SplitHead2=right(head5,2),head2 from tempCTE where head2 is not null
union
select distinct head1,left(head6,2) ,right(head6,2),head3 from tempCTE where head3 is not null
union
select distinct head1,left(head7,2),right(head7,2),head4 from tempCTE where head4 is not null
)
select * from resultCTE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.