Click here to Skip to main content
14,882,280 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to write a query to fetch data of item code and max date along with its corresponding column values lies in that row.

I tried below code and it gives mupltiple rows for each item code.I want only one row
for each itemcode along with max date and other column data.

any help would be greatfull

query output:

now it might be only two item codes its just smaple data some times it may conatin 5 or 10 itemcodes please suggest consider this point

what i want from this query is just one row based on maximum date for itemcode


What I have tried:

select purdet.c_batch_no batch_No,purmst.c_bill_no bill_No,max(purmst.d_bill_date) bill_Date,purmst.n_srno srno,purdet.c_item_code item_Code
from pur_mst purmst
join pur_det purdet on purdet.c_br_code=purmst.c_br_code and purdet.c_year=purmst.c_year
and purmst.c_prefix=purdet.c_prefix and purdet.n_srno=purmst.n_srno
where purdet.c_item_code + '/' + purdet.c_batch_no in('000211/AL','000365/GG')
group by purdet.c_batch_no,purmst.c_bill_no,purmst.n_srno,purdet.c_item_code
Updated 12-Sep-19 1:37am

GROUP BY doesn't work as you think: each column you add to the GROUP BY list increases the number of rows you return, not decreases it.
Have a look here: SQL GROUP By and the "Column 'name' is invalid in the select list because..." error[^] - it explains how to use it.
What you need to do is two queries: One to return the max Date for each batch:
SELECT batch_no, MAX(bill_Date) FROM MyTable
GROUP BY Batch_no
Then use JOIN to combine that information with your table again to get just the rows you need.

By the way: If those dates are stored as strings, you need to change that: you should always store data in appropriate datatypes: DATE in this case. String comparisons are made on a character by character basis with the whole result being based on the first difference encountered - which works provided no-one added "01-02-2019" to you DB by mistake later on ... storing them as DATE, DATETIME, or DATETIME2 gets rid of that problem.
Dear Programmer,
As per the requirement , its is possible by sub query as i have written.
kindly put it in your programming.



This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900