I have two very simple tables in Oracle 9G:
Customer
userid | firstName | lastName | email
-------+-----------+----------+---------------------
1 user1 User1 user1#mail.in
2 user2 User2 user2#mail.in
Order
orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+-------
1 1 0 12/12/2009 1
2 1 1 13/12/2009 2
3 1 1 14/12/2009 3
4 2 0 12/12/2009 4
5 2 1 16/12/2009 2
6 1 0 14/12/2009 5
7 2 1 17/12/2009 4
8 2 0 10/12/2010 2
I want to select all users which have orders of type 0
select *
from Customer c
inner join Order o on c.userid = o.userid
where o.orderType = '0'
The result is:
orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
1 1 0 12/12/2009 1
4 2 0 12/12/2009 4
6 1 0 14/12/2009 5
8 2 0 10/12/2010 2
Now I need to modify this query to bring only last purchase date for each user id and get the result like this:
orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
6 1 0 14/12/2009 5
8 2 0 10/12/2010 2
How should I modify my query to get this result?
SELECT *
FROM order o
WHERE o.orderType ='0'
AND o.order_date =
( SELECT MAX(o2.order_date)
FROM order o2
WHERE o2.userid = o.userid
AND o2.orderType = '0'
)
or
SELECT o.*
FROM order o
JOIN
( SELECT userid
, MAX(order_date) AS lastPurchaseDate
FROM order
WHERE o.orderType ='0'
GROUP BY userid
) AS grp
ON grp.userid = o.userid
AND grp.lastPurchaseDate = o.order_date
Try this:
select *
from customer c
, order o
where c.userid = o.userid
and o.orderType ='0'
and o.order_date = (
select max(o2.order_date)
from order o2
where o2.userid = o.userid
)
No subquery required, just aggregate functions.
select c.userId, o.OrderType,
max(o.Order_Date),
max(o.orderiD) keep (dense_rank last order by order_date),
max(o.Amount) keep (dense_rank last order by order_date)
from Customer c inner join Order o
on c.userid = o.userid where o.orderType ='0'
group by c.userId, o.OrderType
SELECT *
FROM Order o
INNER JOIN
(SELECT MAX(o.id) AS maxid
FROM Customer c
INNER JOIN Order o ON c.userid = o.userid
WHERE o.orderType ='0'
GROUP BY c.userid) x ON x.maxid = o.id
Related
I have 3 rows of data returned from a query
OrderId | OtherId
--------+---------
1234 | 444
1234 | 555
1234 | 666
How to return data in this format
OrderId | OtherId | OtherId2 | OtherId
--------+---------+----------+--------
1234 | 444 | 555 | 666
Can I use Distinct for this problem?
EDIT
The result set comes from a query such as
left join (
Select distinct
o.id
,OL2.db
,case
when i.cust = 'cust2' then
case
when
lower(pdf.dept) not like 'abc%' or pdf.dept is null
then 'Yes'
else'No'
end
else 'Yes'
end as 'Show'
,otherId
from order o with(nolock)
Join instance i with(nolock) on i.id = o.id
Join orderLine ol with(nolock) on ol.id = o.SocialNetworker_Order_InstanceId
and ol.id = o.id
join product p with(nolock) on o.id = p.id
and ol.id = p.id
left join productEx pdf with(nolock) on p.id = pdf.id
and o.id = pdf.id
Where i.cust in ('cust1')
) ol2 on OL2.id = sno.id
and OL2.id2 = sno.id2
and i.db = cc.db
How to work solution into the above code?
You can use row_number() and conditional aggregation:
select orderid,
max(case when seqnum = 1 then otherid end) as otherid_1,
max(case when seqnum = 2 then otherid end) as otherid_2,
max(case when seqnum = 3 then otherid end) as otherid_3
from (select t.*, row_number() over (partition by orderid order by otherid) as seqnum
from t
) t
group by orderid;
Use an outer join with cascading join conditions:
select t1.OrderId, t1.OtherId OtherId1, t2.OtherId OtherId2, t3.OtherId OtherId3
from orders t1
left join orders t2 on t2.OrderId = t1.OrderId
and t2.OtherId > t1.OtherId
left join orders t3 on t3.OrderId = t2.OrderId
and t3.OtherId > t2.OtherId
If there are less than 3 other ids, the right-most columns will be null.
This query will work on pretty much any database.
I am trying to write a SQL statement that will return a set of Distinct set of CompanyNames from a table based on the most recent SaleDate withing a specified date range from another table.
T01 = Account
T02 = TransHeader
The fields of importance are:
T01.ID, T01.CompanyName
T02.AccountID, T02.SaleDate
T01.ID = T02.AccountID
What I want to return is the Max SaleDate for each CompanyName without any duplicate CompanyNames and only the Max(SaleDate) as LastSale. I will be using a Where Clause to limit the SaleDate range.
I tried the following but it returns all the records for all SalesDates in the range. This results in the same company being listed multiple times.
Current MS-SQL Query
SELECT T01.CompanyName, T02.LastSale
FROM
(SELECT DISTINCT ID, IsActive, ClassTypeID, CompanyName FROM Account) T01
FULL OUTER JOIN
(SELECT DISTINCT AccountID, TransactionType, MAX(SaleDate) LastSale FROM TransHeader group by AccountID, TransactionType, SaleDate) T02
ON T01.ID = T02.AccountID
WHERE ( ( T01.IsActive = 1 )AND
( (Select Max(SaleDate)From TransHeader Where AccountID = T01.ID AND TransactionType in (1,6) AND SaleDate is NOT NULL)
BETWEEN '01/01/2016' AND '12/31/2018 23:59:00' AND (Select Max(SaleDate)From TransHeader Where AccountID = T01.ID AND TransactionType in (1,6) AND SaleDate is NOT NULL) IS NOT NULL
)
)
ORDER BY T01.CompanyName
I thought the FULL OUTER JOIN was the ticket but it did not work and I am stuck.
Sample data Account Table (T01)
ID CompanyName IsActive ClassTypeID
1 ABC123 1 1
2 CDE456 1 1
3 EFG789 1 1
4 Test123 0 1
5 Test456 1 1
6 Test789 0 1
Sample data Transheader table (T02)
AccountID TransactionType SaleDate
1 1 02/03/2012
2 1 03/04/2013
3 1 04/05/2014
4 1 05/06/2014
5 1 06/07/2014
6 1 07/08/2015
1 1 08/09/2016
1 1 01/15/2016
2 1 03/20/2017
2 1 03/21/2017
3 1 03/04/2017
3 1 04/05/2018
3 1 05/27/2018
4 1 06/01/2018
5 1 07/08/2018
5 1 08/01/2018
5 1 10/11/2018
6 1 11/30/2018
Desired Results
CompanyName LastSale (Notes note returned in the result)
ABC123 01/15/2016 (Max(SaleDate) LastSale for ID=1)
CDE456 03/21/2017 (Max(SaleDate) LastSale for ID=2)
EFG789 05/27/2018 (Max(SaleDate) LastSale for ID=3)
Testing456 10/11/2018 (Max(SaleDate) LastSale for ID=5)
ID=4 & ID=6 are note returned because IsActive = 0 for these records.
One option is to select the maximum date in the select clause.
select
a.*,
(
select max(th.saledate)
from transheader th
where th.accountid = a.id
and th.saledate >= '2016-01-01'
and th.saledate < '2019-01-01'
) as max_date
from account a
where a.isactive = 1
order by a.id;
If you only want to show transaction headers with sales dates in the given date range, then you can just inner join the maximum dates with the accounts. In order to do so, you must group your date aggregation per account:
select a.*, th.max_date
from account a
join
(
select accountid, max(saledate) as max_date
from transheader
and saledate >= '2016-01-01'
and saledate < '2019-01-01'
group by accountid
) th on th.accountid = a.id
where a.isactive = 1
order by a.id;
select CompanyName,MAX(SaleDate) SaleDate from Account a
inner join Transheader b on a.id = b.accountid
group by CompanyName
order by 1
I would like to achieve the following and to be honest, I don't even know where to start. We have two tables, Customers and Orders. I need to create a third table, which will have combined data, and displayed in a horizontal way.
Those are the current tables:
CUSTOMERS:
Id Email Language
Customer1 1 cust1#email.com en
Customer2 2 cust2#email.com sp
Customer3 3 cust3#email.com ru
ORDERS:
Id CustomerId Total
a 1 200
b 1 300
c 2 400
d 3 500
e 3 500
f 3 500
g 3 500
And the desired outcome:
CustomerID Email Language Order1 Order2 Order3 Order4 Order5 Order6
1 a b - - - -
2 c - - - - -
3 d e f g - -
Each customer can have up to 6 active orders, but the logic can also be that for each customer only the 6 first orders will be listed.
Any suggestions on how to achieve this result? Your help will be greatly appreciated.
SQL tables represent unordered tables. There is no ordering unless a column specifies the ordering. Let me assume that id plays that role.
Then, you can do this with conditional aggregation:
select c.id, c.email, c.language,
max(case when seqnum = 1 then o.id end) as order_1,
max(case when seqnum = 2 then o.id end) as order_2,
max(case when seqnum = 3 then o.id end) as order_3,
max(case when seqnum = 4 then o.id end) as order_4,
max(case when seqnum = 5 then o.id end) as order_5,
max(case when seqnum = 6 then o.id end) as order_6
from customers c left join
(select o.*,
row_number() over (partition by customerid order by id) as seqnum
from orders o
) o
on c.customerid = o.customerid
group by c.id, c.email, c.language;
My tables looks like this:
For each TimeOfDay I would like to get the most frequent Category. For example if there are 3 auctions with unique ClosedTime but each of this Time has TimeOfDay=1 and 2 of these auctions have CategoryId=1 and one auction CategoryId=2 I would like to get:
TimeOfDay | CategoryId
1 | 1
I have tried group by TimeOfDay and CategoryId but still I don't know how to get top category for each TimeOfDay group. I have this:
select t.TimeOfDay, a.CategoryId, count(a.CategoryId)
numberOfSalesInCategory
from Auction a
join Time t on t.Id = a.ClosedTime
where IsSuccess = 1
group by t.TimeOfDay, a.CategoryId
and result for some sample data:
TimeOfDay | CategoryId | numberOfSalesInCategory
0 1 1
1 1 1
1 2 3
2 2 1
0 3 1
3 3 1
3 4 2
So for these data I would like to get:
TimeOfDay | CategoryId
0 | 1 or 3 numberOfSalesInCategory for both is 1
1 | 2 numberOfSalesInCategory is 3
2 | 2 only one category
3 | 4 numberOfSalesInCategory is 2
Technically, you are looking for the mode. There can be multiple modes, if multiple values all have the same frequency. If you are happy to arbitrarily choose one, then a conditional aggregation with row_number() is the solution:
select TimeOfDay,
max(case when seqnum = 1 then CategoryId end) as ModeCategory
from (select t.TimeOfDay, a.CategoryId, count(*) as numberOfSalesInCategory,
row_number() over (partition by t.TimeOfDay order by count(*) ) as seqnum
from Auction a join
Time t
on t.id = a.ClosedTime
where a.isSuccess = 1
group by t.TimeOfDay, a.CategoryId
) ta
group by TimeOfDay;
You could put the current statement in a CTE, rank them with RANK() and then do a stuff statement.
e.g.
; WITH T AS (SELECT t.TimeOfDay, a.CategoryId, COUNT(a.CategoryId)
numberOfSalesInCategory
FROM Auction a
JOIN Time t ON t.Id = a.ClosedTime
WHERE IsSuccess = 1
GROUP BY t.TimeOfDay, a.CategoryId)
, S AS (SELECT T.*
, RANK() OVER (PARTITION BY TimeOfDay ORDER BY numberOfSalesInCategory DESC) RankOrder
FROM T)
SELECT DISTINCT TimeOfDay
, STUFF(((SELECT ' or ' + CONVERT(NVARCHAR, CategoryId)
FROM S
WHERE RankOrder = 1
AND TimeOfDay = BloobleBlah.TimeOfDay
FOR XML PATH('')), 1, 4, '') CategoryId
FROM S BloobleBlah
I have the following simplified tables:
tblOrders
orderID date
---------------------
1 2013-10-04
2 2013-10-05
3 2013-10-06
tblOrderLines
lineID orderID ProductCategory
--------------------------------------
1 1 10
2 1 3
3 1 10
4 2 3
5 3 3
6 3 10
7 3 10
I want to select records from tblOrders ONLY if any order line has ProductCategory = 10. So, if none of the lines of a particular order has ProductCategory = 10, then do not return that order.
How would I do that?
This should do:
SELECT *
FROM tblOrders O
WHERE EXISTS(SELECT 1 FROM tblOrderLines
WHERE ProductCategory = 10
AND OrderID = O.OrderID)
You can use exists for this
Select o.*
From tblOrders o
Where exists (
Select 1
From tblOrderLines ol
Where ol.ProductCategory = 10
And ol.OrderId = o.OrderId
)
try this
SELECT DISTINCT orderId
FROM tblOrders t1
INNER JOIN tblOrderLines t2 ON t1.orderId = t2.orderId
WHERE t2.ProductCategory = 10
Try this:
SELECT *
FROM tblOrders O
JOIN tblOrderLines L
ON O.orderID = L.orderID
WHERE L.OrderID in (SELECT orderID FROM tblOrderLines WHERE ProductCategory = 10)