Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hi everyone,I am new to SQL and I need assistance with what I consider a difficult query. I need to find a count of the orders that have been opened, closed, or postponed for a given date range.The name of the table is ORDERS and the fields I need to work with are: EventDate, and OrderStatus. Here is an example of what the data in the table looks like:EventDate OrderStatus 7/5/2008 Opened7/5/2008 Closed7/5/2008 Closed7/6/2008 Opened7/7/2008 Opened7/8/2008 Postponed7/8/2008 ClosedHere is what the result needs to look like:EventDate Opened Closed Postponed7/5/2008 1 2 07/6/2008 1 0 07/7/2008 1 0 07/8/2008 0 0 1I this possible? Thanks in advance ROTORTORQUE
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2008-07-14 : 01:08:10
This is very much possible. just do like this.
SELECT EventDate,SUM(CASE WHEN OrderStatus='Opened' THEN 1 ELSE 0 END) AS Opened,SUM(CASE WHEN OrderStatus='Closed' THEN 1 ELSE 0 END) AS Closed,SUM(CASE WHEN OrderStatus='Postponed' THEN 1 ELSE 0 END) AS Postponed FROM ORDERSGROUP BY EventDate
SwePeso
Patron Saint of Lost Yaks
30421 Posts
Posted - 2008-07-14 : 03:40:50
[code]SELECT p.EventDate, p.Opened, p.Closed, p.PostponedFROM Orders AS oPIVOT ( COUNT(OrderStatus) FOR OrderStatus IN ([Opened], [Closed], [Postponed]) ) AS p[/code]E 12°55'05.25"N 56°04'39.16"