What I am trying to achieve (Table View)
Part No 01/02/15 02/02/15 03/02/15 04/02/15 05/02/15 06/02/15
PU1234 24 25 15 22 27 21
PU5678 25 22 19 21 24 26
Table of Data
A B C D E Part Name Date & Time
FX01 FN50 X82 OP.70 Packing PU4238TZA 2015-02-27 03:43:55.000
FX01 FN50 X82 OP.70 Packing PU4238TZA 2015-02-27 03:43:56.000
FX01 FN50 X82 OP.70 Packing PU4238TZA 2015-02-27 03:43:57.000
FX01 FN50 X82 OP.70 Packing PU4238TZA 2015-02-27 03:43:58.000
I want the code to be generic so I can manipulate it to achieve all of the below
- Quantity per part number per hour (24 hour period) stored procedure 1
- Quantity per part number per day (between two dates) stored procedure 2
- Quantity per part number per week (between two dates) stored procedure 3
- Quantity per part number per Month (between two dates) stored procedure 4
The code below works (to a fashion) but populates the table with all zero's
`;with cte as(
select
[CAB Part No.], cast([Date & Time] as date) UtcDay, DATEPART(hour, [Date & Time]) UtcHour, count(*) as Counts
from [dbo].[SFDLOG]
where [Date & Time] between '2015-02-01' and '2015-02-02'
group by
cast([Date & Time] as date), DATEPART(hour,[Date & Time]),[CAB Part No.]
)
select dateadd(hour, utchour, cast(utcday as datetime)) as [SFD Hour],
Counts
into #TempDates
from cte
select *
from
(
select [CAB Part No.],[SFD Hour],
convert(CHAR(10),[SFD Hour], 120) PivotDate
from #tempDates
left join [SFDLOG]
on [SFD Hour] between '2015-02-01' and '2015-02-02'
) x
pivot
(
count([SFD Hour])
for PivotDate in ([2015-02-01 00:00:00.000], [[2015-02-01 01:00:00.000], 2015-02-01 02:00:00.000],
) p;
drop table #tempdates`