select with count for years

后端 未结 1 1154
面向向阳花
面向向阳花 2021-01-25 03:10

I have pickup table which looks like this

create table Pickup
(
PickupID int IDENTITY,
ClientID int ,
PickupDate date ,
PickupProxy  varchar (200) ,
PickupHispa         


        
相关标签:
1条回答
  • 2021-01-25 03:34

    Best way to structure a query like this is to use an Index table. Ideally create this in your master database so it is available to all dbs on the server but can be created in the local db too.

    You can create one like this

    create table IndexTable
    (
    IndexID int NOT NULL,
    Primary Key (IndexID),
    );
    

    Then fill it with the numbers 1 - n where n is big enough, say 1,000,000.

    Like this

    INSERT IndexTable
    VALUES (1)
    
    WHILE (SELECT MAX(IndexID) FROM IndexTable) < 1000000
    INSERT IndexTable
    SELECT IndexID + (SELECT MAX(IndexID) FROM IndexTable)
    FROM IndexTable 
    

    Your query then uses this table to treat months as integers

    SELECT DATEADD(month, 0, i.IndexID) Months
          ,COUNT(p.PickupDate)
          ,AVERAGE(*Whatever*)
    FROM Pickup p
         INNER JOIN
         IndexTable i ON DATEDIFF(month, p.PickupDate, 0) = i.IndexID
    GROUP BY i.IndexID
    WITH ROLLUP
    
    0 讨论(0)
提交回复
热议问题