Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Gabungkan beberapa baris menjadi satu baris

Anda tidak dapat memiliki nomor dinamis kolom seperti itu, tetapi Anda dapat menggabungkan data Anda menjadi string:

select
    s.ItemID, s.Code, s.Name,
    stuff(
        (
            select ', ' + CAST(sv.SearchValueID AS VARCHAR)
            from ItemSearch as sv
            where sv.ItemID = s.ItemID
            for xml path(''), type
        ).value('.', 'nvarchar(128)')
    , 1, 2, '') as SearchValues
from Item as s;

atau Anda dapat memutar baris dengan PIVOT command atau secara manual (Saya lebih suka pendekatan yang terakhir, sepertinya lebih fleksibel bagi saya, tetapi pivot dapat sangat mengurangi jumlah kode dalam situasi tertentu ):

with cte as (
    select
        *,
        row_number() over(partition by sv.ItemID order by sv.SearchValueID) as row_num
    from ItemSearch as sv
)
select
    s.ItemID, s.Code, s.Name,
    max(case when sv.row_num = 1 then sv.SearchValueID end) as SearchValueID1,
    max(case when sv.row_num = 2 then sv.SearchValueID end) as SearchValueID2,
    max(case when sv.row_num = 3 then sv.SearchValueID end) as SearchValueID3,
    max(case when sv.row_num = 4 then sv.SearchValueID end) as SearchValueID4
from Item as s
    inner join cte as sv on sv.ItemID = s.ItemID
group by s.ItemID, s.Code, s.Name

Anda juga dapat mengubah pernyataan sebelumnya menjadi SQL dinamis seperti ini:

declare @stmt nvarchar(max)

select
    @stmt = 
        isnull(@stmt + ',','') + 
        'max(case when sv.row_num = ' + cast(rn as nvarchar(max)) +
        ' then sv.SearchValueID end) as SearchValueID' + cast(rn as nvarchar(max))
from (
    select distinct row_number() over(partition by ItemID order by SearchValueID) as rn
    from ItemSearch
) as a

select @stmt = '
    with cte as (
        select
            *,
            row_number() over(partition by sv.ItemID order by sv.SearchValueID) as row_num
        from ItemSearch as sv
    )
    select
        s.ItemID, s.Code, s.Name,' + @stmt + '
    from Item as s
        inner join cte as sv on sv.ItemID = s.ItemID
    group by s.ItemID, s.Code, s.Name;'

exec dbo.sp_executesql @stmt = @stmt

demo biola sql




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara Menambahkan Batasan Kunci Asing ke Tabel yang Ada di SQL Server (T-SQL)

  2. Melewati tipe tabel yang ditentukan pengguna antara database SQL Server

  3. Apa itu kebuntuan dalam database?

  4. sp_executesql lambat dengan parameter

  5. SQL - Mengkloning record dan turunannya