SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 joins instead of subqueries
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

kwacz23
Starting Member

44 Posts

Posted - 03/19/2014 :  09:03:38  Show Profile  Reply with Quote
Hi

How to change below query for JOiNS query

select * from Sales.Orders a
where a.orderid in ( select max(b.orderid) from sales.orders b
where b.custid=a.custid)

Task : Finad for every user max order ID

Regards

webfred
Flowing Fount of Yak Knowledge

Germany
8764 Posts

Posted - 03/19/2014 :  09:26:23  Show Profile  Visit webfred's Homepage  Reply with Quote
select custid, max(orderid) as orderid from sales.orders group by custid


Too old to Rock'n'Roll too young to die.
Go to Top of Page

sqlsaga
Yak Posting Veteran

USA
93 Posts

Posted - 03/19/2014 :  11:05:29  Show Profile  Reply with Quote
Use this...

;WITH CTE AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY CustID ORDER BY OrderID Desc) AS Rnum
FROM Sales.Orders
)
SELECT Column_Names
FROM CTE WHERE Rnum = 1

Read more about ranking functions at http://sqlsaga.com/sql-server/what-is-the-difference-between-rank-dense_rank-row_number-and-ntile-in-sql-server/

Visit www.sqlsaga.com for more t-sql snippets and BI related how to's.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000