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

SQL Server:laporan lanjutan dari beberapa baris menjadi satu

Anda dapat menggunakan SQL dinamis untuk memecahkan masalah ini -- atau jika hanya untuk satu set data, tulis dengan tangan. Dalam kedua kasus Anda akan berakhir dengan sesuatu yang terlihat seperti ini:

SELECT R1.userid, R1.lesson, 
       R1.response as loc_nameA_resp, R1.lable as loc_nameA_labl, R1.weight as loc_nameA_weig, R1.duration_seconds as loc_nameA_dura,
       R2.response as loc_nameB_resp, R2.lable as loc_nameB_labl, R2.weight as loc_nameB_weig, R2.duration_seconds as loc_nameB_dura,
--- etc for each question
FROM user U
JOIN response R1 on R1.userid = u.userid and R1.lesson = 'first' and R1.question = 'loc_nameA'
JOIN response R2 on R2.userid = u.userid and R2.lesson = 'first' and R2.question = 'loc_nameB'
--- etc for each question
WHERE
   U.userid = 'bob' -- this does not need to be bob, whatever user you want.

Ini dia, diuji, dan segalanya.

DECLARE @sqlSelectList varchar(max);
DECLARE @sqlJoinList varchar(max);

SELECT @sqlSelectList = '', @sqlJoinList='';

WITH Questions AS
(
  SELECT DISTINCT question
  FROM ResultsChoices
)
SELECT -- We use the question as the alias for join uniqueness,
       -- We could increment a number but why bother?
  @sqlJoinList = @sqlJoinList +
     ' JOIN ResultsChoices '+question+' on '+question+'.userid = u.userid and '+question+'.question = '''+question+'''', 
  @sqlSelectList = @sqlSelectList +
     ', '+question+'.response as '+question+'_resp, '+question+'.label as '+question+'_labl, '+question+'.weight as '+question+'_weig, '+question+'.duration_seconds as '+question+'_dura '
FROM Questions;

DECLARE @sql NVARCHAR(max);

SET @sql = N'SELECT DISTINCT u.userid ' + @sqlSelectList + N' FROM #ResultsChoices u ' + @sqlJoinList;

EXEC sp_executesql @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. Kunci Asing ke beberapa tabel

  2. Memilih tanggal terbaru di antara dua kolom

  3. Argumen Opsional dalam Klausa WHERE

  4. Tally Table untuk memasukkan tanggal yang hilang di antara dua tanggal? SQL

  5. Melewati parameter dinamis ke prosedur tersimpan di SQL Server 2008