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

TSQL Finding Order, der fandt sted i 3 på hinanden følgende måneder

Rediger: Slet eller MAX() OVER (PARTITION BY ...) da det så ud til at dræbe præstationen.

;WITH cte AS ( 
SELECT    CustID  ,
          OrderDate,
          DATEPART(YEAR, OrderDate)*12 + DATEPART(MONTH, OrderDate) AS YM
 FROM     Orders
 ),
 cte1 AS ( 
SELECT    CustID  ,
          OrderDate,
          YM,
          YM - DENSE_RANK() OVER (PARTITION BY CustID ORDER BY YM) AS G
 FROM     cte
 ),
 cte2 As
 (
 SELECT CustID  ,
          MIN(OrderDate) AS Mn,
          MAX(OrderDate) AS Mx
 FROM cte1
GROUP BY CustID, G
HAVING MAX(YM)-MIN(YM) >=2 
 )
SELECT     c.CustName, o.OrderDate, YEAR(o.OrderDate) AS YEAR
FROM         Customers AS c INNER JOIN
                      Orders AS o ON c.CustID = o.CustID
INNER JOIN  cte2 c2 ON c2.CustID = o.CustID and o.OrderDate between Mn and Mx
order by c.CustName, o.OrderDate


  1. hvordan man skriver sql-forespørgsel for at vælge rækker med maks. værdi i én kolonne

  2. Fylder en kombinationsboks med mysql-data

  3. Indsæt flere noder til xml-feltet i en enkelt forespørgsel

  4. Hvordan installeres PLV8 på Windows?