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

Cara ORDER BY di SQL PIVOT

Coba ini:

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. cara membuat data Anda horizontal

  2. TSQL:Bagaimana cara mengubah waktu lokal ke UTC? (SQLServer 2008)

  3. Ekspresi Tabel Umum, mengapa titik koma?

  4. Pemecahan masalah kebuntuan di Sql Server 2008

  5. Menerapkan fungsi agregat MIN ke bidang BIT