Link to home
Start Free TrialLog in
Avatar of maqskywalker
maqskywalker

asked on

sql server 2008 query

Hi experts,

I have a sql server 2008 table called MyTestTable

It looks like this:

User generated image
Here is the scrip to create this table:

CREATE TABLE [dbo].[MyTestTable](
	[Region] [int] NULL,
	[Year] [int] NULL,
	[OrderNo] [int] NULL,
	[ItemCost] [smallmoney] NULL,
	[Status] [varchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[MyTestTable] ([Region], [Year], [OrderNo], [ItemCost], [Status]) VALUES (1, 2013, 1001, 5.0000, N'Closed')
INSERT [dbo].[MyTestTable] ([Region], [Year], [OrderNo], [ItemCost], [Status]) VALUES (1, 2013, 1001, 10.0000, N'Closed')
INSERT [dbo].[MyTestTable] ([Region], [Year], [OrderNo], [ItemCost], [Status]) VALUES (1, 2013, 1001, 6.0000, N'Open')
INSERT [dbo].[MyTestTable] ([Region], [Year], [OrderNo], [ItemCost], [Status]) VALUES (1, 2013, 1001, 4.0000, N'Open')

Open in new window


I'm trying to group this table by Region, Year, OrderNo

I then want to Sum the ItemCost column.

For the Status column, this is what I need.

If all 4 items have a value of Closed then show this column when it's collapsed as Closed.

So if at least one the the items for this OrderNo has a value of Open then this column should show as Open when it's collapsed.

For example currently there are two items with a status of Closed and two items with a value of Open. So then the value in this column should show Open and my resulting query should show this:

User generated image
Right now this is the query I have but it's not giving me the result I want shown above:

SELECT [Region]
      ,[Year]
      ,[OrderNo]
      ,SUM ([ItemCost]) As Cost
      ,[Status]
FROM [Test].[dbo].[MyTestTable]
GROUP BY [Region]
        ,[Year]
        ,[OrderNo]
        ,[Status]

How can I fix my query? Can anyone help? thanks.

So to summarize you can look at this image of sample values.
The only time the Status should say Closed is when all items are closed as shown in the 4th item in the picture below.

User generated image
Avatar of Lowfatspread
Lowfatspread
Flag of United Kingdom of Great Britain and Northern Ireland image

try using specifying it as   max(status)
SOLUTION
Avatar of appari
appari
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial