Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Hourly Output

Author  Topic 

mcujardo
Starting Member

5 Posts

Posted - 2011-12-19 : 00:34:59
Dear All,

I need your help. I am trying to create a report that will reflect the hourly out put of a manufacturing line.

I need to display the hourly out put per shift.

Example

HOUR OUTPUT
6:00 PM 100
7:00 PM 200
8:00 PM 100
9:00 PM 100
10:00 PM 50
11:00 PM 300
12:00 PM 100
13:00 PM 100
14:00 PM 100

The query that I have below, queries the user output per hour. My problem is that, how do I display 0 for the hour that does not have an output?

Example, the query below will display

HOUR OUTPUT
6:00 PM 100
7:00 PM 200
8:00 PM 100
9:00 PM 100
11:00 PM 300
13:00 PM 100
14:00 PM 100


SELECT SUM(ip.qty_prod)AS 'Good Quantity',
DATEADD(HH, DATEDIFF(HOUR, 0, ip.created_at_local), 0) as 'Hour',
s.shift_desc AS 'Shift'
FROM item_prod ip INNER JOIN shift s ON ip.shift_id=s.shift_id
WHERE (spare1 IS NOT NULL AND ip.good_prod=1) AND (ip.ent_id='116' AND s.shift_desc = 'A')
GROUP BY DATEADD(HH, DATEDIFF(HOUR, 0, ip.created_at_local), 0), s.shift_desc
ORDER BY DATEADD(HH, DATEDIFF(HOUR, 0, ip.created_at_local), 0)

I need to display

HOUR OUTPUT
6:00 PM 100
7:00 PM 200
8:00 PM 100
9:00 PM 100
10:00 PM 0
11:00 PM 300
12:00 PM 0
13:00 PM 100
14:00 PM 100

Thanks

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-19 : 01:03:58
you need a tally/number table for that

;With Hours(N)
AS
(
SELECT 0
UNION ALL
SELECT N+1
FROM Hours
WHERE N+1 <=23
)
SELEC CONVERT(time,DATEADD(hh,n.N,0)) AS Hour,COALESCE([Good Quantity],0) AS [Output]
FROM Hours h
LEFT JOIN (
SELECT SUM(ip.qty_prod)AS 'Good Quantity',
DATEPART(hh,DATEADD(HH, DATEDIFF(HOUR, 0, ip.created_at_local), 0)) as 'Hour',
s.shift_desc AS 'Shift'
FROM item_prod ip INNER JOIN shift s ON ip.shift_id=s.shift_id
WHERE (spare1 IS NOT NULL AND ip.good_prod=1) AND (ip.ent_id='116' AND s.shift_desc = 'A')
GROUP BY DATEPART(hh,DATEADD(HH, DATEDIFF(HOUR, 0, ip.created_at_local), 0)), s.shift_desc
)t
ON t.[Hour] = h.N
ORDER BY t.Hour



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -