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

Masalah kueri SQL

CREATE TABLE #Garden (Id INT, Name VARCHAR(20))
INSERT INTO #Garden
SELECT 1, 'myGarden' UNION ALL
SELECT 2, 'yourGarden'

CREATE TABLE #Flowers (GardenId INT, Flower VARCHAR(20))
INSERT INTO #Flowers
SELECT  1, 'rose'  UNION ALL
SELECT  1, 'tulip'  UNION ALL
SELECT  2, 'thistle' 

DECLARE @ColList nvarchar(max)

SELECT @ColList = ISNULL(@ColList + ',','') + QUOTENAME('Flower' + CAST(ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS VARCHAR))
FROM #Flowers WHERE GardenId = (
SELECT TOP 1 GardenId
FROM #Flowers
ORDER BY COUNT(*) OVER (PARTITION BY GardenId) DESC

)

EXEC (N'
;WITH cte As
(
SELECT *, ''Flower'' + CAST(ROW_NUMBER() OVER (PARTITION BY GardenId ORDER BY (SELECT 0)) AS VARCHAR) RN
FROM #Flowers F
)
SELECT Name,' + @ColList + N'
FROM cte 
JOIN #Garden g ON g.Id = GardenId
PIVOT (MAX(Flower) FOR RN IN (' + @ColList + N')) Pvt')


DROP TABLE #Garden
DROP TABLE #Flowers

Kembali

Name                 Flower1              Flower2
-------------------- -------------------- --------------------
myGarden             rose                 tulip
yourGarden           thistle              NULL


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana cara mendapatkan Insert id di MSSQL di PHP?

  2. Bergabung dengan MAX catatan tanggal dalam grup

  3. Cari Tahu apakah Batasan CHECK adalah Level Kolom atau Level Tabel di SQL Server (Contoh T-SQL)

  4. Cara Mendapatkan Definisi Kolom Terhitung di SQL Server menggunakan T-SQL

  5. "Permintaan tidak diizinkan di Waitfor" Kesalahan 101 di SQL Server