sql >> Databáze >  >> RDS >> Sqlserver

SQL dotaz pro rozdělení dat sloupců do řádků

Pro tento typ oddělení dat bych navrhoval vytvořit funkci rozdělení:

create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))       
returns @temptable TABLE (items varchar(MAX))       
as       
begin      
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@slice)       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return 
end;

Chcete-li to potom použít v dotazu, můžete použít outer apply pro připojení ke stávajícímu stolu:

select t1.code, s.items declaration
from yourtable t1
outer apply dbo.split(t1.declaration, ',') s

Což povede k výsledku:

| CODE |  DECLARATION |
-----------------------
|  123 |     a1-2 nos |
|  123 |  a2- 230 nos |
|  123 |    a3 - 5nos |

Viz SQL Fiddle with Demo

Nebo můžete implementovat verzi CTE podobnou této:

;with cte (code, DeclarationItem, Declaration) as
(
  select Code,
    cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem,
         stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration
  from yourtable
  union all
  select code,
    cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem,
    stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration
  from cte
  where Declaration > ''
) 
select code, DeclarationItem
from cte


  1. Příklad externí tabulky Oracle

  2. Průvodce návrhem databáze pro newsletter v MySQL

  3. PostgreSQL:Udělte veškerá oprávnění uživateli v databázi PostgreSQL

  4. Načítání třídy com.mysql.jdbc.Driver ... je zastaralá zpráva