Showing posts with label max. Show all posts
Showing posts with label max. Show all posts

Monday, March 12, 2012

Group By, Max(date) query problem

Hello all:

I have an invoice header and detail tables and a customer table using sqlserver 2005. The Detail invoice table has price and product id. The header has the date and customerID.

I need to create a list of the most recent invoice date (and the product price) for each product for each customer. I can't use the group by because when I select both the max(date) and the price (as well as the productID and customerID which all have to be included in the group by) , I get more than one date per product per customer. I can only get the most recent date when I leave out the price and headerdetailID from the field selection.

Any help would be appreciated. Here is sample data & results.

invoiceHeadertable

invheaderID CustomerID InvoiceDate

1 40 1/1/2006

2 40 4/1/2006

3 80 3/1/2006

4 80 7/1/2006

5 80 8/12/2006

invoicedetailtable

invdetail ID invheaderID productcode price

11 1 AA 1.50

12 1 BB 1.30

13 1 CC 1.00

21 2 AA 1.40

23 2 CC 2.00

24 3 AA 2.00

25 3 CC 2.10

26 3 EE 1.10

27 4 AA 1.00

28 4 CC 2.00

29 4 EE 0.99

34 5 EE 1.55

CustomerTable

CustomerID Customername

40 johnCorp

80 maryCorp

Results

customer product most recent invoice(for this product) price

JohnCorp 40 AA 4/1/2006 1.40

JohnCorp 40 BB 1/1/2006 1.30

JohnCorp 40 CC 4/1/2006 2.00

maryCorp 80 AA 7/1/2006 1.40

maryCorp 80 CC 7 /1/2006 2.00

maryCorp 80 EE 8/12/2006 1.55

Something like this 'should' work for you. (Untested)

SELECT
dt.Customer,
dt.Product,
dt.InvoiceDate
d.Price
FROM InvoiceDetailTable d
JOIN ( SELECT
Customer,
Product,
InvoiceDate = max( InvoiceDate )
FROM InvoiceHeaderTable h
JOIN InvoiceDetailTable d
ON h.InvHeaderID = d.InvHeaderID
GROUP BY
Customer,
Product
) dt
ON ( d.Customer = dt.Customer
AND d.Product = dt.Product
AND d.InvoiceDate = dt.InvoiceDate
)

|||Crapola, didn't check your tables first. So ignore the prevoius exercise in 'egg on my face'.|||

IF there was no more than one invoice per day for a customer, you could, in the derived table (dt), include in the SELECT list:

InvHeaderID = max( InvHeaderID )

And then JOIN ON InvHeaderID instead of the three fields I indicated.

Of course, if there were two invoices for the same customer in a day, that would still not be the correct solution.

|||

Well, most of the time there would only be one invoice. But as is always the case, there can be an exception.

I had also wondered if the rank and partition function in sql server 2005 could apply, then one could just use a select query (if this is possible) to return the # 1 invoice per group but I have found no examples showing this used in a group by and where there are multiple tables involved.

Thanks

smhaig

|||

select

ct.CustomerName as Customer,

ct.CustomerID as CustomerID,

idt.ProductCode as Product,

iht.InvoiceDate as MostRecentInvoiceDate,

idt.Price as Price

from InvoiceDetailTable as idt

join InvoiceHeaderTable as iht

on idt.invheaderID = iht.invheaderID

join CustomerTable as ct

on ct.CustomerID = iht.CustomerID

where not exists

(select 1

from InvoiceDetailTable as idtx

join InvoiceHeaderTable as ihtx

on idtx.InvHeaderID = ihtx.InvHeaderID

where idtx.ProductCode = idt.ProductCode

and ihtx.CustomerID = iht.CustomerID

and ihtx.InvoiceDate > iht.InvoiceDate)

order by

ct.CustomerName,

idt.ProductCode

|||

-- Using SQL Server 2005

set nocount on
set dateformat mdy

create table invoiceHeadertable(invheaderID int,CustomerID int,InvoiceDate datetime)
insert into invoiceHeadertable(invheaderID ,CustomerID ,InvoiceDate )
select 1, 40, '1/1/2006' union all
select 2, 40, '4/1/2006' union all
select 3, 80, '3/1/2006' union all
select 4, 80, '7/1/2006' union all
select 5, 80, '8/12/2006'

create table invoicedetailtable(invdetailID int, invheaderID int, productcode char(2), price decimal(5,2))
insert into invoicedetailtable(invdetailID , invheaderID , productcode , price )
select 11, 1, 'AA', 1.50 union all
select 12, 1, 'BB', 1.30 union all
select 13, 1, 'CC', 1.00 union all
select 21, 2, 'AA', 1.40 union all
select 23, 2, 'CC', 2.00 union all
select 24, 3, 'AA', 2.00 union all
select 25, 3, 'CC', 2.10 union all
select 26, 3, 'EE', 1.10 union all
select 27, 4, 'AA', 1.00 union all
select 28, 4, 'CC', 2.00 union all
select 29, 4, 'EE', 0.99 union all
select 34, 5, 'EE', 1.55


create table CustomerTable(CustomerID int, Customername varchar(10))
insert into CustomerTable(CustomerID , Customername )
select 40, 'johnCorp' union all
select 80, 'maryCorp';

with cte(customer,product,[most recent invoice(for this product)],price,rn)
as (
select c.Customername,
d.productcode,
h.InvoiceDate,
d.price,
rank() over(partition by c.Customername,d.productcode order by h.InvoiceDate desc)
from CustomerTable c
inner join invoiceHeadertable h on h.CustomerID=c.CustomerID
inner join invoicedetailtable d on d.invheaderID=h.invheaderID
)
select customer,
product,
[most recent invoice(for this product)],
price
from CTE
where rn=1
order by customer,product

|||

I want to thank Mark and Ron for their solutions and Arnie for getting me to think about two invoices on the same day for the same product and customer (which do exist actually).

I found these solutions to be on the level of advanced lessons for me to study. I have always had trouble with group by when I needed a unique ID on a table where I was selecting a max or min or first one, etc. on another field in the same table.

I have not found any good examples other than very basic ones for rank and partition so if anyone has a good site let me know. Meanwhile I will study what I have as I now have two great ways to solve my problem.

I did not give a duplicate item with my sample data so I will see how this sql 2005 query deals with this. I seem to remember something about ties and ranking and perhaps I could also use select distinct when I select the rank = 1.

The second standard sql query (Ron's) shows me both invoices when there are 2 on same date. It may be that this is the way the data should be displayed if the prices are different, so I will need to check further on that and see if I can tweak these 2 queries to deal with that.

Thank you all again

smHaig

|||

And my thanks to Mark for demonstrating the more modern solution of the two!

Ron

Friday, March 9, 2012

group by qst

In the following query I want to return as a last column the aggregate max
value of the OrderInList field.
input >>
select *, max(OrderInList) as MaxOrderInList
from tbl_activities
where Center_ID = 81
and Fiscal_Year = '2006-2007'
group by *
order by OrderInList
output >>
Column 'tbl_activities.Activity_ID' is invalid in the select list because it
is not contained in either an aggregate function or the GROUP BY clause.
Can I achieve what I want by including the extra MaxOrderInList column
instead of returning an output param?
TIAalto wrote:
> In the following query I want to return as a last column the aggregate max
> value of the OrderInList field.
> input >>
> select *, max(OrderInList) as MaxOrderInList
> from tbl_activities
> where Center_ID = 81
> and Fiscal_Year = '2006-2007'
> group by *
> order by OrderInList
> output >>
> Column 'tbl_activities.Activity_ID' is invalid in the select list because
it
> is not contained in either an aggregate function or the GROUP BY clause.
> Can I achieve what I want by including the extra MaxOrderInList column
> instead of returning an output param?
> TIA
>
Don't be lazy, specify your field list and stop using SELECT *. Any
non-aggregate field that is listed in your field list must also be
included in your GROUP BY clause, like this:
SELECT col1, col2, col3, MAC(col4)
FROM table
GROUP BY col1, col2, col3
It's generally considered bad practice to use "SELECT *".|||You can't GROUP BY *, and you shouldn't use SELECT * in production code
anyway.
It's really not that hard to generate a list of the columns in the table,
however what do you expect to happen here? If you have data like this:
ActivityID OrderInList
1 1
1 2
What is your desired output?
If you group by ALL columns, then your max(OrderInList) is meaningless.
Try it:
CREATE TABLE dbo.floob
(
ActivityID INT,
OrderInList INT
);
SET NOCOUNT ON;
INSERT dbo.floob(ActivityID,OrderInList)
SELECT 1,1
UNION ALL
SELECT 1,2;
SELECT
ActivityID, OrderInList,
MAXOrderInList = MAX(OrderInList)
FROM
dbo.floob
GROUP BY
ActivityID, OrderInList;
-- maybe what you meant was:
SELECT
ActivityID,
MAXOrderInList = MAX(OrderInList)
FROM
dbo.floob
GROUP BY
ActivityID;
GO
DROP TABLE dbo.floob;
GO
Without proper DDL, sample data and desired results, I have little else to
offer, except that grouping by all columns in the table doesn't make any
sense.
http://www.aspfaq.com/5006
"alto" <altodorov@.hotmail.com> wrote in message
news:%23VHcK%23emGHA.2204@.TK2MSFTNGP03.phx.gbl...
> In the following query I want to return as a last column the aggregate max
> value of the OrderInList field.
> input >>
> select *, max(OrderInList) as MaxOrderInList
> from tbl_activities
> where Center_ID = 81
> and Fiscal_Year = '2006-2007'
> group by *
> order by OrderInList
> output >>
> Column 'tbl_activities.Activity_ID' is invalid in the select list because
> it is not contained in either an aggregate function or the GROUP BY
> clause.
> Can I achieve what I want by including the extra MaxOrderInList column
> instead of returning an output param?
> TIA
>|||Last column is to return the same value for all records, like this
ActivityID, other cols..., MaxOrderInList
1 1,... 2
1 2,... 2
And BTW, in response to Tracy I'd already tried w/ all the fields in the
goup by - it wouldn't allow me to include an aggregate column in the list.
Again I could return the max OrderInList in an output param; I'm just asking
if the alternative above is possible.
Txs!
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:uX8gRLfmGHA.4816@.TK2MSFTNGP03.phx.gbl...
> You can't GROUP BY *, and you shouldn't use SELECT * in production code
> anyway.
> It's really not that hard to generate a list of the columns in the table,
> however what do you expect to happen here? If you have data like this:
> ActivityID OrderInList
> 1 1
> 1 2
> What is your desired output?
> If you group by ALL columns, then your max(OrderInList) is meaningless.
> Try it:
> CREATE TABLE dbo.floob
> (
> ActivityID INT,
> OrderInList INT
> );
> SET NOCOUNT ON;
> INSERT dbo.floob(ActivityID,OrderInList)
> SELECT 1,1
> UNION ALL
> SELECT 1,2;
> SELECT
> ActivityID, OrderInList,
> MAXOrderInList = MAX(OrderInList)
> FROM
> dbo.floob
> GROUP BY
> ActivityID, OrderInList;
> -- maybe what you meant was:
> SELECT
> ActivityID,
> MAXOrderInList = MAX(OrderInList)
> FROM
> dbo.floob
> GROUP BY
> ActivityID;
> GO
> DROP TABLE dbo.floob;
> GO
>
> Without proper DDL, sample data and desired results, I have little else to
> offer, except that grouping by all columns in the table doesn't make any
> sense.
> http://www.aspfaq.com/5006
>
> "alto" <altodorov@.hotmail.com> wrote in message
> news:%23VHcK%23emGHA.2204@.TK2MSFTNGP03.phx.gbl...
>|||"alto" <altodorov@.hotmail.com> wrote in message
news:OT2ZkSfmGHA.4868@.TK2MSFTNGP04.phx.gbl...
> Last column is to return the same value for all records, like this
> ActivityID, other cols..., MaxOrderInList
> 1 1,... 2
> 1 2,... 2
> And BTW, in response to Tracy I'd already tried w/ all the fields in the
> goup by - it wouldn't allow me to include an aggregate column in the list.
What doesn't "wouldn't allow me" mean? Did you get an error message? What
was it? What code did you try?
I think you would have to do this with a correlated subquery, not group by.
For example, using the DDL and sample data I provided earlier:
SELECT
ActivityID,
OrderInList,
MaxOrderInList = (
SELECT MAX(OrderInList)
FROM dbo.floob
WHERE ActivityID = f.ActivityID
)
FROM
dbo.floob f;
A|||>> Last column is to return the same value for all records [sic], like this ..<<
Try a scalar subquery expression
SELECT a, b, c, ...
(SELECT MAX(order_in_list) FROM Foobar) AS order_in_list_max
FROM Foobar;|||I mean I tried this query
select *, max(OrderInList) as MaxOrderInList
from tbl_activities
where Center_ID = 81
and Fiscal_Year = '2006-2007'
group by Activity_ID,
Center_ID,
Category_ID,
Type_of_Activity ,
[Description] ,
Location_Activity ,
Date_Activity ,
Total_number_of_attendies ,
Purpose_activity ,
Fully_organized_by_org ,
Partial_assistance_of_org ,
BeginingDate_FY ,
Fiscal_Year ,
memo ,
IsRequest ,
ProposedGuest ,
ActivityType ,
DateStart ,
DateEnd ,
DateCreated ,
max(OrderInList)
order by OrderInList
w/ this result:
Server: Msg 144, Level 15, State 1, Line 26
Cannot use an aggregate or a subquery in an expression used for the group by
list of a GROUP BY clause.
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:eJsIHWfmGHA.856@.TK2MSFTNGP03.phx.gbl...
> "alto" <altodorov@.hotmail.com> wrote in message
> news:OT2ZkSfmGHA.4868@.TK2MSFTNGP04.phx.gbl...
> What doesn't "wouldn't allow me" mean? Did you get an error message?
> What was it? What code did you try?
> I think you would have to do this with a correlated subquery, not group
> by. For example, using the DDL and sample data I provided earlier:
> SELECT
> ActivityID,
> OrderInList,
> MaxOrderInList = (
> SELECT MAX(OrderInList)
> FROM dbo.floob
> WHERE ActivityID = f.ActivityID
> )
> FROM
> dbo.floob f;
>
> A
>|||Bingo, it worked:
input >>
select Activity_ID,
Center_ID,
Category_ID,
Type_of_Activity ,
[Description] ,
Location_Activity ,
Date_Activity ,
Total_number_of_attendies ,
Purpose_activity ,
Fully_organized_by_org ,
Partial_assistance_of_org ,
BeginingDate_FY ,
Fiscal_Year ,
memo ,
IsRequest ,
ProposedGuest ,
ActivityType ,
DateStart ,
DateEnd ,
DateCreated,
(select max(OrderInList) from tbl_activities where Center_ID = 81 and
Fiscal_Year = '2006-2007') as MaxOrderInList
from tbl_activities
where Center_ID = 81
and Fiscal_Year = '2006-2007'
group by Activity_ID,
Center_ID,
Category_ID,
Type_of_Activity ,
[Description] ,
Location_Activity ,
Date_Activity ,
Total_number_of_attendies ,
Purpose_activity ,
Fully_organized_by_org ,
Partial_assistance_of_org ,
BeginingDate_FY ,
Fiscal_Year ,
memo ,
IsRequest ,
ProposedGuest ,
ActivityType ,
DateStart ,
DateEnd ,
DateCreated ,
--(select max(OrderInList) from tbl_activities where Center_ID = 81 and
Fiscal_Year = '2006-2007')
OrderInList
order by OrderInList
output (see last column returned) >>
1309 81 1 NULL activite 1 emplacement 1 NULL NULL NULL NULL 2006-2007 1
1 2006-06-19 00:00:00.000 2006-06-24 00:00:00.000 2006-06-27 09:24:57.007 2
1310 81 1 NULL activite 2 emplacement 2 NULL NULL NULL NULL 2006-2007 1
4 2006-06-05 00:00:00.000 2006-06-17 00:00:00.000 2006-06-27 09:25:21.550 2
Txs!
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1151418422.623163.134150@.x69g2000cwx.googlegroups.com...
> Try a scalar subquery expression
> SELECT a, b, c, ...
> (SELECT MAX(order_in_list) FROM Foobar) AS order_in_list_max
> FROM Foobar;
>|||>I mean I tried this query
> select *, max(OrderInList) as MaxOrderInList
And like I said before, selecting all columns and then aggregating one of
them doesn't make sense.
A|||alto wrote:
> I mean I tried this query
> select *, max(OrderInList) as MaxOrderInList
> from tbl_activities
> where Center_ID = 81
> and Fiscal_Year = '2006-2007'
> group by Activity_ID,
> Center_ID,
> Category_ID,
> Type_of_Activity ,
> [Description] ,
> Location_Activity ,
> Date_Activity ,
> Total_number_of_attendies ,
> Purpose_activity ,
> Fully_organized_by_org ,
> Partial_assistance_of_org ,
> BeginingDate_FY ,
> Fiscal_Year ,
> memo ,
> IsRequest ,
> ProposedGuest ,
> ActivityType ,
> DateStart ,
> DateEnd ,
> DateCreated ,
> max(OrderInList)
> order by OrderInList
> w/ this result:
> Server: Msg 144, Level 15, State 1, Line 26
> Cannot use an aggregate or a subquery in an expression used for the group
by
> list of a GROUP BY clause.
>
**THINK** about what you're doing here. Your aggregate value (MAX) is
calculated by grouping together like values from the table. The value
of MAX is unknown until that grouping has been done, so HOW can you
include it in the grouping criteria?
As I said before, STOP USING SELECT *, be specific about the fields that
you want returned by the SELECT, and include those fields (excluding the
aggregate) in your GROUP BY.

Wednesday, March 7, 2012

Group by on the text colum throws error

Hi ,

I have this query

paprojnumber is varchar
patx500 is text
palineitemseq is int

select Paprojnumber,Patx500,max(palineitemseq) from pa02101,pa01601
where
pa02101.pabillnoteidx=pa01601.pabillnoteidx group by
paprojnumber,patx500

it throws this error
Server: Msg 306, Level 16, State 2, Line 1
The text, ntext, and image data types cannot be compared or sorted,
except when using IS NULL or LIKE operator.

Thanks a lot for your help.

AJHere it means exactly what the error says. You cannot sort on a text field
(or NText field), which is what your "group by" code is trying to do.

"AJ" <aj70000@.hotmail.com> wrote in message
news:6097f505.0409300838.a81c800@.posting.google.co m...
> Hi ,
> I have this query
> paprojnumber is varchar
> patx500 is text
> palineitemseq is int
> select Paprojnumber,Patx500,max(palineitemseq) from pa02101,pa01601
> where
> pa02101.pabillnoteidx=pa01601.pabillnoteidx group by
> paprojnumber,patx500
> it throws this error
> Server: Msg 306, Level 16, State 2, Line 1
> The text, ntext, and image data types cannot be compared or sorted,
> except when using IS NULL or LIKE operator.
> Thanks a lot for your help.
> AJ|||On Thu, 30 Sep 2004 18:24:58 +0100, Robin Tucker wrote:

> Here it means exactly what the error says. You cannot sort on a text field
> (or NText field), which is what your "group by" code is trying to do.

You can, however, group by an expression using it:

select Paprojnumber,Patx500,max(palineitemseq)
from pa02101,pa01601
where pa02101.pabillnoteidx=pa01601.pabillnoteidx
group by paprojnumber,convert(varchar(50),patx500)

Group by Max Query

Could any one help me how the Query should look like
I have three tables: Asset_Table, Assignment_Table and User_Table
Output should be: Asset_Number from Asset_Table where Asset_Number = 123, Date from Assignment_Table = MAX Date and First Name from User_Table
Thnx
PatrickMaybe
select asset_number, firstname , (select max(date) from Assignment_table
where assignment_table.id = asset_table.id)
from assignment_Table inner join User_table on assignment_Table.key =user_table.key
where asset_number = 123
Wayne Snyder MCDBA, SQL Server MVP
Computer Education Services Corporation (CESC), Charlotte, NC
(Please respond only to the newsgroups.)
I support the Professional Association for SQL Server
(www.sqlpass.org)
"Patrick" <patrick.thie@.nl.mci.com> wrote in message
news:57B2D2A0-9656-4700-9616-E7A60EF4BEC9@.microsoft.com...
> Could any one help me how the Query should look like!
> I have three tables: Asset_Table, Assignment_Table and User_Table.
> Output should be: Asset_Number from Asset_Table where Asset_Number = 123,
Date from Assignment_Table = MAX Date and First Name from User_Table.
> Thnx,
> Patrick

Group by Max Count ? how to do query?

Can anyone tell me how to do this query please?
3 fields. provider, site, visitdate. Given a date range for
visitdate,
Return all providers that have at least one visit in that date range
and also display which site has the most visitdates for EACH provider
for all records (not date constrained).
Since a provider can have visits at multiple sites I only want to
return the site where they have the most visits.
THANKS A LOTSome DDL (i.e. create table statements) would be useful.
Thomas
<bringmewater@.gmail.com> wrote in message
news:1114630228.267194.170960@.g14g2000cwa.googlegroups.com...
> Can anyone tell me how to do this query please?
> 3 fields. provider, site, visitdate. Given a date range for
> visitdate,
> Return all providers that have at least one visit in that date range
> and also display which site has the most visitdates for EACH provider
> for all records (not date constrained).
> Since a provider can have visits at multiple sites I only want to
> return the site where they have the most visits.
> THANKS A LOT
>|||Try,
create view v1
as
select
provider,
site,
count(*) as number_of_visit
from
t1
where
visitdate >= convert(char(8), @.sd, 112) and visitdate < dateadd(day, 1,
convert(char(8), @.ed, 112))
group by
provider,
site
having
count(*) > 0
go
select
provider,
site,
number_of_visit
from
v1 as a
where
number_of_visit = (select max(b.number_of_visit) from v1 as b where
b.provider = a.provider)
go
AMB
"bringmewater@.gmail.com" wrote:

> Can anyone tell me how to do this query please?
> 3 fields. provider, site, visitdate. Given a date range for
> visitdate,
> Return all providers that have at least one visit in that date range
> and also display which site has the most visitdates for EACH provider
> for all records (not date constrained).
> Since a provider can have visits at multiple sites I only want to
> return the site where they have the most visits.
> THANKS A LOT
>

Sunday, February 26, 2012

group by clause Query help

This is my query

select ano,max(date),a_subject from MY_TAB where table_name='xyz' and
ano=877
group by a_subject,ano order by a_subject

ANOmax(Date)A_Subject
8772005-01-20 00:00:00.000Subject_1
8771900-01-01 00:00:00.000Subject_2
8772004-12-20 00:00:00.000Subject_3
8772005-01-19 00:00:00.000Subject_4
-----------------------
When I put the status column in, it fetches all the rows.

select ano,max(date),a_subject,status from MY_TAB where
table_name='xyz' and ano=877 group by a_subject,ano,status order by
a_subject

ANOmax(Date)A_SubjectStatus
8772005-01-20 00:00:00.000Subject_1Not Started
8771900-01-01 00:00:00.000Subject_2Not Started
8772004-12-20 00:00:00.000Subject_3Completed
8771900-01-01 00:00:00.000Subject_3Not Started
8771900-01-01 00:00:00.000Subject_4Not Started
8772005-01-19 00:00:00.000Subject_4Not Started
----------------------
now what i want is

ANOmax(Date)A_SubjectStatus
8772005-01-20 00:00:00.000Subject_1Not Started
8771900-01-01 00:00:00.000Subject_2Not Started
8772004-12-20 00:00:00.000Subject_3Completed
8772005-01-19 00:00:00.000Subject_4Not Started
Thanks a lot for your help.

AJ[posted and mailed, please reply in news]

(aj70000@.hotmail.com) writes:
> select ano,max(date),a_subject from MY_TAB where table_name='xyz' and
> ano=877
> group by a_subject,ano order by a_subject
> ANO max(Date) A_Subject
> 877 2005-01-20 00:00:00.000 Subject_1
> 877 1900-01-01 00:00:00.000 Subject_2
> 877 2004-12-20 00:00:00.000 Subject_3
> 877 2005-01-19 00:00:00.000 Subject_4
> -----------------------
> When I put the status column in, it fetches all the rows.
> select ano,max(date),a_subject,status from MY_TAB where
> table_name='xyz' and ano=877 group by a_subject,ano,status order by
> a_subject
> ANO max(Date) A_Subject Status
> 877 2005-01-20 00:00:00.000 Subject_1 Not Started
> 877 1900-01-01 00:00:00.000 Subject_2 Not Started
> 877 2004-12-20 00:00:00.000 Subject_3 Completed
> 877 1900-01-01 00:00:00.000 Subject_3 Not Started
> 877 1900-01-01 00:00:00.000 Subject_4 Not Started
> 877 2005-01-19 00:00:00.000 Subject_4 Not Started
> ----------------------
> now what i want is
> ANO max(Date) A_Subject Status
> 877 2005-01-20 00:00:00.000 Subject_1 Not Started
> 877 1900-01-01 00:00:00.000 Subject_2 Not Started
> 877 2004-12-20 00:00:00.000 Subject_3 Completed
> 877 2005-01-19 00:00:00.000 Subject_4 Not Started
> Thanks a lot for your help.

With the example you have given, you would get away with:

select ano,max(date),a_subject, MIN(status)
from MY_TAB
where table_name='xyz' and ano=877
group by a_subject,ano
order by a_subject

But this does not work well, if you have Status values like "Anticipating"
which represents intermediate stages.

If you are looking for the status on the selected date, then this might be
better:

SELECT a.ano, a.maxdate, a.a_subject, b.status
FROM (select ano, maxdate, max(date), a_subject
from MY_TAB
where table_name='xyz' and ano=877
group by a_subject, ano) AS b
JOIN MY_TAB b ON a.ano = b.ano
AND a.maxdate = b.date
AND a.a_subject = b.a_subject

This assumes that ano/a_subject/date constitutes some form of key in
the table.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Here is how a SELECT works in SQL ... at least in theory. Real
products will optimize things when they can.

a) Start in the FROM clause and build a working table from all of the
joins, unions, intersections, and whatever other table constructors are
there. The table expression> AS <correlation name> option allows you
give a name to this working table which you then have to use for the
rest of the containing query.

b) Go to the WHERE clause and remove rows that do not pass criteria;
that is, that do not test to TRUE (reject UNKNOWN and FALSE). The
WHERE clause is applied to the working set in the FROM clause.

c) Go to the optional GROUP BY clause, make groups and reduce each
group to a single row, replacing the original working table with the
new grouped table. The rows of a grouped table must be group
characteristics: (1) a grouping column (2) a statistic about the group
(i.e. aggregate functions) (3) a function or (4) an expression made up
those three items.

d) Go to the optional HAVING clause and apply it against the grouped
working table; if there was no GROUP BY clause, treat the entire table
as one group.

e) Go to the SELECT clause and construct the expressions in the list.
This means that the scalar subqueries, function calls and expressions
in the SELECT are done after all the other clauses are done. The
"AS" operator can also give names to expressions in the SELECT
list. These new names come into existence all at once, but after the
WHERE clause, GROUP BY clause and HAVING clause has been executed; you
cannot use them in the SELECT list or the WHERE clause for that reason.

If there is a SELECT DISTINCT, then redundant duplicate rows are
removed. For purposes of defining a duplicate row, NULLs are treated
as matching (just like in the GROUP BY).

f) Nested query expressions follow the usual scoping rules you would
expect from a block structured language like C, Pascal, Algol, etc.
Namely, the innermost queries can reference columns and tables in the
queries in which they are contained.

g) The ORDER BY clause is part of a cursor, not a query. The result
set is passed to the cursor, which can only see the names in the SELECT
clause list, and the sorting is done there. The ORDER BY clause cannot
have expression in it, or references to other columns because the
result set has been converted into a sequential file structure and that
is what is being sorted.

As you can see, things happen "all at once" in SQL, not from left to
right as they would in a sequential file/proceudral language model. In
those languages, these two statements produce different results:
READ (a, b, c) FROM File_X;
READ (c, a, b) FROM File_X;

while these two statements return the same data:

SELECT a, b, c FROM Table_X;
SELECT c, a, b FROM Table_X;

Think about what a confused mess this statement is in the SQL model.

SELECT f(c2) AS c1, f(c1) AS c2 FROM Foobar;
That is why such nonsense is illegal syntax.

Friday, February 24, 2012

Group by and Case Statements

Hi,
I have a query where I am using a case statement and a group by e.g.
Select Field1, Field2, Field3, Max(Field4),
CASE
WHEN <something> THEN ' '
WHEN <something> THEN 1
END as Field4
WHERE <something>
GROUP BY Field1, Field2, Field3, Field4
The problem I am having is the group by isn't using the value from
the Case Statement, it's not grouping the records correctly. Anyone
have any idea's why that would happen?
Thanks for the helpBy definition, the expressions in the GROUP BY clause reffer to the
columns from the table, not to the columns defined in the SELECT
clause. You probably need to use a subquery for this:
SELECT Field1, Field2, Field3, MAX(Field4), TheExpression as Field4
FROM (
SELECT Field1, Field2, Field3, Field4,
CASE
WHEN <something> THEN ' '
WHEN <something> THEN 1
END as TheExpression
FROM <your table>
WHERE <something>
) x
GROUP BY Field1, Field2, Field3, TheExpression
Razvan|||Thanks, that's what I figured. I was hoping there was a more eligant
way around that.
Thanks|||Simply copy the same CASE expression used in the SELECT list into the
GROUP BY:
Select Field1, Field2, Field3, Max(Field4),
CASE
WHEN <something> THEN ' '
WHEN <something> THEN 1
END as Field4
WHERE <something>
GROUP BY Field1, Field2, Field3,
CASE
WHEN <something> THEN ' '
WHEN <something> THEN 1
END
Roy Harvey
Beacon Falls, CT
On 3 May 2006 09:25:44 -0700, "Red2" <sdibello@.gmail.com> wrote:

>Hi,
> I have a query where I am using a case statement and a group by e.g.
> Select Field1, Field2, Field3, Max(Field4),
> CASE
> WHEN <something> THEN ' '
> WHEN <something> THEN 1
> END as Field4
> WHERE <something>
> GROUP BY Field1, Field2, Field3, Field4
> The problem I am having is the group by isn't using the value from
>the Case Statement, it's not grouping the records correctly. Anyone
>have any idea's why that would happen?
>Thanks for the help|||Red2 wrote:
> Hi,
> I have a query where I am using a case statement and a group by e.g.
> Select Field1, Field2, Field3, Max(Field4),
> CASE
> WHEN <something> THEN ' '
> WHEN <something> THEN 1
> END as Field4
> WHERE <something>
> GROUP BY Field1, Field2, Field3, Field4
> The problem I am having is the group by isn't using the value from
> the Case Statement, it's not grouping the records correctly. Anyone
> have any idea's why that would happen?
--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1
It'd be better if you showed the actual query. Your example has a
Max(Field4) and the CASE expression is labeled as Field4. If the GROUP
BY clause has Field4 is will be grouping the Field4 in the Max()
function. Obviously, not what you want to do. Is this a misnomer or
are you really using the same column in the Max() function and as the
CASE expression's name?
If you want to GROUP BY the result of a CASE expression you have to
include the CASE expression in the GROUP BY clause:
GROUP BY field1, field2, field3, CASE WHEN <something> THEN X ELSE Y END
--
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)
--BEGIN PGP SIGNATURE--
Version: PGP for Personal Privacy 5.0
Charset: noconv
iQA/AwUBRFkUgYechKqOuFEgEQLZ2ACdHDbb0StLG/MEkaOpME4KfeDYTfcAn1I2
EEZOhQ/brevVe0gSJNujPhER
=aD2k
--END PGP SIGNATURE--

group by

I have table
date,type,price
date and price is changing
i need to group it, to have
max(date), type and price (from the row with max date)
it's no problem to take
max(date) and type bat without the third column, i need all columns
HelpUSE Northwind
GO

SET NOCOUNT ON
CREATE TABLE myTable99([date] datetime, type char(10), price money
, PRIMARY KEY (type, [date]))
GO

INSERT INTO myTable99([date],type,price)
SELECT '1/1/2001','bat' ,10.00 UNION ALL
SELECT '1/1/2002','bat' ,20.00 UNION ALL
SELECT '1/1/2003','bat' ,30.00 UNION ALL
SELECT '1/1/2004','bat' ,40.00 UNION ALL
SELECT '1/1/2001','ball',40.00 UNION ALL
SELECT '1/1/2002','ball',30.00 UNION ALL
SELECT '1/1/2003','ball',20.00 UNION ALL
SELECT '1/1/2004','ball',10.00
GO

SELECT l.*
FROM myTable99 AS l
JOIN ( SELECT type, MAX([date]) AS MAX_date
FROM myTable99
GROUP BY type) AS r
ON l.type = r.type
AND l.[date] = r.MAX_date

SET NOCOUNT OFF
DROP TABLE myTable99
GO|||Long thanks