sql >> Databasteknik >  >> RDS >> Sqlserver

Hur man beställer efter i SQL PIVOT

Prova detta:

with Mth (st, nd) as ( 
  select DATEADD (M, datediff (m, 0,'2012-09-01'), 0), 
         DATEADD (M, DATEDIFF (m, 0, '2012-09-01') + 1, 0)   
  union all 
  select DATEADD (m, 1, st), 
         DATEADD (m, 1, nd) 
  from Mth 
  where nd <= DATEADD (m, datediff (m, 0, getdate()), 0)
), Pivoted
AS
(     
    select * 
    from 
    ( 
      select MONTH(Mth.st) Month, 
          U.USER, 
          COUNT(S.QRY_ID) Searches 
      FROM Mth 
      LEFT JOIN SEARCHES S 
        on Mth.st <= S.CREATED 
        and Mth.nd > S.CREATED 
      LEFT JOIN MEMBERS U 
        on U.AID = S.AID 
      GROUP BY YEAR(Mth.st), MONTH(Mth.st), U.HOLDER_LOGIN
    ) src 
    pivot 
    ( 
      sum(searches) 
      for month in ([12],[11],[10]) 
    ) piv
)
SELECT * 
FROM Pivoted
ORDER BY Dec



  1. Hur man undkommer värde nyckelord i mysql medan du använder Select-satsen

  2. Runda .NET DateTime millisekunder, så det kan passa SQL Server millisekunder

  3. PostgreSQL använder inte ett partiellt index

  4. Postgis + boost::geometry + C++