select with count for years

2019-03-01 08:30发布

问题:

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