Advertisement
iEfimoff

Sub-queries + json generator

Feb 3rd, 2020
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.33 KB | None | 0 0
  1. WITH Nominations (NominationID, winnersFirstPlace, winnersSecondPlace, winnersThirdPlace)
  2. AS
  3. (
  4.    SELECT NominationID, [1], [2], [3] FROM
  5.    (
  6.        SELECT NominationID
  7.             , IssuerID
  8.             , Pos
  9.          FROM Nominations
  10.         WHERE Pos IN (1, 2, 3)
  11.         GROUP BY NominationID
  12.                , IssuerID
  13.                , Pos
  14.    ) s
  15.    pivot
  16.    (
  17.        MAX(IssuerID) FOR Pos IN ([1], [2], [3])
  18.    ) p
  19. )
  20. SELECT an.CYear 'year'
  21.     , CASE WHEN an.OpenName LIKE '%сектор%экономи%' THEN 3
  22.            ELSE an.GroupID
  23.       END 'statistics.nominationType'
  24.     , an.OpenName 'statistics.nominationName'
  25.     , (SELECT ai.OpenName FROM Issuers ai WHERE ai.IssuerID = n.winnersFirstPlace) 'statistics.winnersFirstPlace'
  26.     , (SELECT ai.OpenName FROM Issuers ai WHERE ai.IssuerID = n.winnersSecondPlace) 'statistics.winnersSecondPlace'
  27.     , (SELECT ai.OpenName FROM Issuers ai WHERE ai.IssuerID = n.winnersThirdPlace) 'statistics.winnersThirdPlace'
  28.     , json_query(SELECT ai.OpenName
  29.                    FROM Issuers ai
  30.                   WHERE ai.IssuerID IN (n.winnersFirstPlace, n.winnersSecondPlace, n.winnersThirdPlace)
  31.                     FOR json path) 'statistics.shortList'
  32.  FROM Nominations n
  33.     , ANominations an
  34. WHERE an.NominationID = n.NominationID
  35. ORDER BY an.CYear DESC
  36.   FOR json path
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement