Question

I am struggling a little bit with an SQL Statement and was hoping if someone would be willing to point me in the right direction.

Below is a picture of my table:

enter image description here

As you can see here I have a column called 'State'. Basically I want to group all 'State' associated with a particular BuildID and display them in an extra column on my SQL output.

I am close but not quite there.

In the next picture below is an example of the statement I have used to try and achieve this:

enter image description here

As you can see here, it has done SUM and added the TotalTime and created the extra columns I require. However instead of grouping it all into one record, it has created 2 extra lines per BuildID. One with the value for the 'Running' state, another record for the value State of 'Break' and another record that contains the value 0 on both States.

Now what I want it to do is group it into one record for each BuildID. Like the picture I have added below:

enter image description here

The above image is how I want the records displayed. But the problem is I have added the WHERE [State] = Running, which I know is wrong but was just using this as an example. As you can see the 'Break' column has no value.

I hope this makes sense and was hoping if someone could point me in the right direction?

Here is an example on SQL fiddle http://sqlfiddle.com/#!3/7b6b9/2

Thanks for taking the time to read this :)

Was it helpful?

Solution

Have refined the sql a bit, here you go:

SELECT BuildID,Product, Program, 
  sum(CASE WHEN State = 'Running' THEN cast(TotalTime as INT) ELSE 0 END) AS Running
  , sum(CASE WHEN State = 'Break' THEN cast(TotalTime as INT) ELSE 0 END) AS Breakt
FROM Line1Log
GROUP BY BuildID,Product, Program

Please check SQLFiddle

Not sure if i am missing something :-), but the solution looks pretty straight forward. Let me know.

OTHER TIPS

move your SUM() OVER(PARTITION BY...) out from CASE

SQL fiddle

select BuildID, Product, Program, Sum(Running) Running, Sum([Break]) [Break]
from (
    SELECT Distinct BuildID, Product, Program, 
    Sum(Case when [State]='Running' Then TotalTime Else 0 END) OVER (Partition by [State], [BuildID]) Running,
    Sum(Case when [State]='Break' Then TotalTime Else 0 END) OVER (Partition by [State], [BuildID]) [Break]

    From Line1Log) T
group by BuildID, Product, Program

Everything else is ok, why are you grouping all columns?, Try this,

Select BuidId,Product,program,Sum(Running),Sum(Break)
(......
.....
......) as T
group by BuidId,Product,program
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top