select with count for years

∥☆過路亽.° 提交于 2019-12-02 06:11:24

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!