Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Invertire/spegnere un GROUP BY

Puoi gestire con un'espressione tabella comune

WITH CTE AS (
    SELECT OwnerNumber,ItemCode,ItemNumber,CountOfItems FROM table

    UNION ALL SELECT OwnerNumber,ItemCode,ItemNumber,CountOfItems-1
    FROM CTE
    WHERE CountOfItems >= 2
)
SELECT OwnerNumber,ItemCode,ItemNumber
FROM CTE
ORDER BY ItemNumber
OPTION (MAXRECURSION 0);

Modifica:

Aggiunto MAXRECURSION per gestire situazioni in cui CountOfItems supera le ricorsioni massime predefinite, come sottolineato da Dev_etter