簡體   English   中英

如何在sql server中從csv格式的文本文件中獲取表格的數據

[英]How to get data of a table filled from a text file with csv format in sql server

這是我從批量導入中獲得的數據,我在名為 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     |

我需要做一個查詢來獲取這樣的數據:

| 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   |

第一行有像標題(描述)這樣的數據,但也有我需要的數據,比如日期和星期幾。

可以做我需要的嗎? 謝謝。

將數據加載到臨時表中,列來自第一行。

然后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 <> ''

請按照以下步驟操作:

  1. 表創建和插入數據

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)
  1. 結果查詢

;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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM