select with count for years

折月煮酒 提交于 2019-12-02 10:49:58

问题


I have pickup table which looks like this

create table Pickup
(
PickupID int IDENTITY,
ClientID int ,
PickupDate date ,
PickupProxy  varchar (200) ,
PickupHispanic bit default 0,
EthnCode varchar(5) ,
CategCode varchar (2) ,
AgencyID int,
Primary Key (PickupID),
);

and it containe pickups for clients I need to create report based on this table which should looks like this


I know i need to use CASE but really do not know how to put years and calculate average pickups for each year. and how to count pickups for specific year.so far i have only this

SELECT
DATEPART(YEAR, PickupDate)as 'Month'

FROM dbo.Pickup 
group by DATEPART(YEAR, PickupDate)
WITH ROLLUP

Any ideas?


回答1:


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


来源:https://stackoverflow.com/questions/15515679/select-with-count-for-years

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