Getting most recent record based on datetime column SQL - c#

I am trying to select the most recent record. Right now it is returning all records. Which makes since, because I have not put in a filter to get most recent, I am unsure of how to do that. Here is my code:
select
c.my_Name, a.my_Num, d.myBrand, a.order_bill, a.myDate
from
[table1] a
left join
[table2] b on a.[myCode] = b.[myCode]
left join
[table3] c on c.myTag = b.myTag
left join
[table4] d on a.[myHash] = d.[myHash]
where
c.[myName] = 'test name'
I am wanting to get most recent record from the table, I am guessing the most efficient way is to get most recent a.myDate.

I'd write
SELECT TOP 1
c.my_Name, a.my_Num, d.myBrand, a.order_bill, CONVERT(char(10), a.myDate,126)
FROM [table1] a
LEFT JOIN [table2] b on a.[myCode] = b.[myCode]
LEFT JOIN [table3] c on c.myTag=b.myTag
LEFT JOIN [table4] d on a.[myHash] = d.[myHash]
WHERE c.[myName] = 'test name'
ORDER BY a.myDate DESC

Something like this might help
select c.my_Name, a.my_Num, d.myBrand, a.order_bill, MAX(a.myDate)
from [table1] a
left join [table2] b on a.[myCode] = b.[myCode]
left join [table3] c on c.myTag=b.myTag
left join [table4] d on a.[myHash] = d.[myHash]
where c.[myName] = 'test name'
group by c.my_Name, a.my_Num, d.myBrand, a.order_bill
order by a.myDate DESC
This will grab distinct records with the greatest (most recent) a.myDate, grouped by your other elements.
Be aware of duplicates. Use your duplicate criteria keys in the select statement, or whatever elements you absolutely need to be distinct.

Related

Return Top 1 from any SQL query/view/CTE

Is there a way to return only ONE record so that I can get all the column calls via the code below?
using (var reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess).ConfigureAwait(false))
{
DataTable dtResults = new DataTable();
dtResults.Load(reader);
return dtResults;
}
So right now this will return ALL X records from the query and I only need to return 1 record so I can plug the columns data types etc. into my Grid control.
We can't just add SELECT Top 1 because some of the queries start with a CTE etc.
We can't wrap it around another query because sometimes the query have Order Bys
We can't force the users to add a separate query that will mimic what we want to do.
Here is the error:
Msg 1033, Level 15, State 1, Line 40
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Here is the query:
SELECT TOP 1 *
FROM
(SELECT O.Department, O.ID
FROM dbo.table1 e
LEFT JOIN dbo.table2 O ON e.Department = O.Department
ORDER BY ID) x
If you need metadata only, use .ExecuteReader(System.Data.CommandBehavior.SchemaOnly)
If you want to read one row, use SQL's OFFSET/FETCH clause. They are appended at the end of the statement, so might work for your case.
https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15
Note that you must provide some ordering clause.
SELECT
O.Department
,O.ID
FROM dbo.table1 e
LEFT JOIN dbo.table2 O
ON e.Department = O.Department
order by O.ID
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
Try the following, you cannot use Order by with sub-query in SQL server.
select top 1 *
from
(
SELECT
O.Department
,O.ID
FROM dbo.table1 e
LEFT JOIN dbo.table2 O
ON e.Department = O.Department
)
Order by
ID
The subquery is just unecessary. You can use top (1) and order by directly in the outer query:
select top(1) o.department, o.id
from dbo.table1 e
left join dbo.table2 o on e.department = o.department
order by id
sp_describe_first_result_set should do what you want. It'll return metadata for the command in question.
exec sp_describe_first_result_set #tsql = N'SELECT O.Department, O.ID
FROM dbo.table1 e
LEFT JOIN dbo.table2 O ON e.Department = O.Department
ORDER BY ID'

Nested Select MySQL statements to LINQ

I'm trying to convert the following MySQL statement in to LINQ query format
SELECT * FROM table1 WHERE table1.id IN (SELECT c_id FROM table2 WHERE a_id IN (1, 49) GROUP BY c_id HAVING COUNT(*) = 2) ORDER BY name
Got as far as this, but I'm drawing a blank on how to handle the IN and 2nd SELECT statement
myItems = from c in table1
let id = c.id
where ????
orderby c.name
select c;
Would appreciate some guidance with this please
Try this:
var ids=new[]{1,49};
var innerquery=table2.Where(e=>ids.Contains(e.a_id))
.GroupBy(e=>e.c_id)
.Where(g=>g.Count()==2)
.Select(g=>g.Key);
var myItems = from c in table1
where innerquery.Contains(c.id)
orderby c.name
select c;
First define your inner query,after the group by you will get a collection of IGrouping<TKey, TElement>> that represent a collection of objects that have a common key, filter the groups choosing only those where count==2, and select the keys of those groups. The second part is really easy to understand. I split the process in two queries to do it more readable, but you can merge both query in one.

MS Access Select Multiple Joins

I'm trying to select by c# and odbc from the following tables.
LinkTab (FromDevID, FromPort, ToDevID, ToPort)
DevList (ID,DevName...)
The result should look like
FromDevName | FromPort | ToDevName | ToDevPort
i tried already the following statement:
SELECT dev1.DevName, lt.FromPort, dev2.DevName, lt.ToPort
FROM (LinkTab lt
INNER JOIN DevList dev1 ON lt.FromDevID = dev1.ID)
INNER JOIN devList dev2 ON lt.ToDevID = dev2.ID
and I couldn't get all records. I guess there is a mistake at my join condition.
Presumably, you need left join:
SELECT dev1.DevName, lt.FromPort, dev2.DevName, lt.ToPort
FROM (LinkTab lt LEFT JOIN
DevList dev1
ON lt.FromDevID = dev1.ID
) LEFT JOIN
devList dev2
ON lt.ToDevID = dev2.ID;
The reason your query would not return all the rows is because the devises may not always match. If this is the case, then INNER JOIN will filter out the rows with unmatched devices. A LEFT JOIN will keep all the rows in the first table, assigning NULL for the columns from the second and third tables.

sql query with complicated join to get unique records list

I need a query that select customer table with right cardId by applied the below cases.
If you have any suggestions, please share.
Possible cases are:
Only one records found - easy, use the Card_id found
No records found - leave blank
More than one record found - use the Card_id that starts with 2000 if available, otherwise pick the one with latest created date (in CustomerCards table)
Customer Table:
ID CardID
1 200132
2 263987
3 100789
..
CustomerCards table
CustomerId CardID CreatedOn
1 209890 12/11/2014
1 200132 12/12/2014
1 100732 11/10/2014
2 168902 12/11/2014
2 263987 15/01/2015
I've started with left join:
select ct.* from dbo.Customer ct
left join dbo.CustomerCard cc
on ct.id = cc.customerId
And a bit stuck after that.
A start
;with cte1 as
(
select cc.CustomerId, cc.CardID, cc.CreatedOn
from dbo.CustomerCard cc
group by cc.CustomerId, cc.CardID, cc.CreatedOn
having count(*) = 1
), cte200 as
(
select cc.CustomerId, cc.CardID, max(cc.CreatedOn)
from dbo.CustomerCard cc
group by cc.CustomerId, cc.CardID
where cc.CardID like '2000%'
)
select cte1
union
select cte2000
union
select ct.ID, ct.CardID, '1/1/1900' as CreatedOn
from dbo.Customer ct
left join dbo.CustomerCard cc
on ct.id = cc.customerId
where cc.customerId is null
union
select cc.ID, cc.CardID, max(cc.CreatedOn)
from dbo.CustomerCard cc
left join cte1
on cte1.customerId = cc.customerId
left join cte2000
on cte2000.customerId = cc.customerId
where cte1.customerId is null
and cte2000.customerId is null
group by cc.ID, cc.CardID

Inner Join Query incorrect result

Hi I am developing an application in VS 2010, C# and SQLCe database.
I am generating a report from 3 tables respectively Income, Expence and Transactions.
table structure is as below:
Income:
Expence:
Transactions:
For this I wrote query
select t.tDate as [Date], t.tDescription as [Detail],e.eAmount as [Debit],
i.iAmount as [Credit], t.balance as [Balance]
from Transactions t
inner join Expence e on t.pid=e.pid
join Income i on t.pid=i.pid
where t.pid='11'
But when I run this query I am just getting
I want that my result should be like a bank statement as below.
As per my understanding query is not right.
How can we write query to get result like this?
You must use the left join, not use Join. Because left return all cases in table from and case exists in table Expence e Income.
select t.tDate as [Date], t.tDescription as [Detail],e.eAmount as [Debit],
i.iAmount as [Credit], t.balance as [Balance]
from Transactions t
left join Expence e on t.pid=e.pid
left join Income i on t.pid=i.pid
where t.pid='11'
If I got it right to join items from Expence table with items from Transactions table you should use pId and eId and to join items from Income you should use pId and iId, so your select would look something like that:
select t.tDate as [Date], t.tDescription as [Detail],e.eAmount as [Debit],
i.iAmount as [Credit], t.balance as [Balance]
from Transactions t
inner join Expence e on t.pid=e.pid and t.eId = e.eId
join Income i on t.pid=i.pid and t.iId = i.iId
where t.pid='11'

Categories