SQL - Pull distinct row based on max value - sql

I am trying to pull the most recent sale amount for each salesperson. The salespeople have made a sale on multiple days, I only want the most recent one.
My attempt below:
SELECT salesperson, amount
FROM table
WHERE date = (SELECT MAX(date) FROM table);

Use correlated subquery :
SELECT t.salesperson, t.amount
FROM table t
WHERE t.date = (SELECT MAX(t1.date)
FROM table t1
WHERE t1.salesperson = t.salesperson -- for each salesperson
);

If you are using PostgreSQL, you can take advantage of DISTINCT ON:
SELECT DISTINCT ON (salesperson) salesperson, amount
FROM table t
ORDER BY salesperson, date DESC
This will return only one row for each salesperson. The ORDER BY clause says to return the one with the largest date for that salesperson.
Unfortunately, DISTINCT ON is not supported by other databases.

Related

MIN and DISTINCT for ORACLE DB

I have this query
SELECT table_article.articleID, table_article_to_date.sellDate, MIN(table_article.price) AS minPrice
FROM table_article table_article
LEFT JOIN table_article_to_date table_article_to_date ON (table_article.ord_no=table_article_to_date.ord_no)
WHERE table_article.price > 0 AND table_article_to_date.sellDate BETWEEN_TWO_DATES
GROUP BY table_article.articleID, table_article_to_date.sellDate, table_article.price
For the sell_date I use a time range. My problem is, that i get more than one entrie each articleID.
I wish to have the lowest price of each articleID in a specified time range. DISTINCT is not woking with MIN
Givs a change to make this with a query?
The problem here is that you are adding the sell date to the GROUP BY clause. TO solve the issue, you need to take it out and make use of subqueries to get it back. To achieve this, you can do an inner join of the query and a query with the id, sell date and prize on the id and prize.
Also, no need for the prize in the group by, since it's already in the MIN.
SELECT articleData.articleId, articleData.sellDate, articleData.price FROM
(
SELECT articleId, MIN(price)
FROM table
[...]
GROUP BY articleId
) AS minPrice
INNER JOIN
(
SELECT articleId, sellDate, price
FROM table
) AS articleData
ON minPrice.price = articleData.price AND minPrice.articleId = articleData.articleId

SELECT AVG(invoiceamount) per debtor where date< date row

I have a SQL table with the following columns: Invoice ID, debtor ID, invoice date and invoice amount. where invoice ID is unique.
I'm trying to create an extra column with the average invoice amount. So per row I want the average invoice amount of the debtor, but only of the invoices where the invoice date <= the invoicedate of the column.
I'm not sure where to start, all ideas are welcome
Try this-
SELECT
A.Invoice_ID,
A.debtor_ID,
A.invoice_date,
A.invoice_amount,
(
SELECT AVG(B.invoice_amount)
FROM your_table B
WHERE B.debtor_ID = A.debtor_ID
AND B.invoice_date <= A.invoice_date
) AS average_invoice_amount
FROM your_table A
You want to use window functions:
select t.*,
avg(invoice_amount) over (partition by debtor_id order by invoice_date) as running_average
from t;
I strongly recommend this over a correlated subquery because it should be much faster -- even if you attempt to optimize the correlated subquery with indexes.

MS-Access: HAVING clause not returning any records

I have a Select query to extract Customer Names and Purchase Dates from a table. My goal is to select only those names and dates for customers who have ordered on more than one distinct date. My code is as follows:
SELECT Customer, PurchDate
FROM (SELECT DISTINCT PurchDate, Customer
FROM (SELECT CDate(FORMAT(DateAdd("h",-7,Mid([purchase-date],1,10)+""+Mid([purchase-date],12,8)), "Short Date")) AS PurchDate,
[buyer-name] AS Customer
FROM RawImport
WHERE sku ALIKE "%RE%"))
GROUP BY Customer, PurchDate
HAVING COUNT(PurchDate)>1
ORDER BY PurchDate
This returns no results, even though there are many customers with more than one Purchase Date. The inner two Selects work perfectly and return a set of distinct dates for each customer, so I believe there is some problem in my GROUP/HAVING/ORDER clauses.
Thanks in advance for any help!
You are doing in the inner select
SELECT DISTINCT PurchDate, Customer
and in the outter select
GROUP BY Customer, PurchDate
That mean all are
having count(*) = 1
I cant give you the exact sintaxis in access but you need something like this
I will use YourTable as a replacement of your inner derivated table to make it easy to read
SELECT DISTINCT Customer, PurchDate
FROM YourTable
WHERE Customer IN (
SELECT Customer
FROM (SELECT DISTINCT Customer, PurchDate
FROM YourTable)
GROUP BY Customer
HAVING COUNT(*) > 1
)
inner select will give you which customer order on more than one day.
outside select will bring you those customer on all those days.
.
Maybe you can try something simple to get the list of customer who brought in more than one day like this
SELECT [buyer-name]
FROM RawImport
WHERE sku ALIKE "%RE%"
GROUP BY [buyer-name]
HAVING Format(MAX(purchase-date,"DD/MM/YYYY")) <>
Format(MIN(purchase-date,"DD/MM/YYYY"))

select multiple records based on order by

i have a table with a bunch of customer IDs. in a customer table is also these IDs but each id can be on multiple records for the same customer. i want to select the most recently used record which i can get by doing order by <my_field> desc
say i have 100 customer IDs in this table and in the customers table there is 120 records with these IDs (some are duplicates). how can i apply my order by condition to only get the most recent matching records?
dbms is sql server 2000.
table is basically like this:
loc_nbr and cust_nbr are primary keys
a customer shops at location 1. they get assigned loc_nbr = 1 and cust_nbr = 1
then a customer_id of 1.
they shop again but this time at location 2. so they get assigned loc_nbr = 2 and cust_Nbr = 1. then the same customer_id of 1 based on their other attributes like name and address.
because they shopped at location 2 AFTER location 1, it will have a more recent rec_alt_ts value, which is the record i would want to retrieve.
You want to use the ROW_NUMBER() function with a Common Table Expression (CTE).
Here's a basic example. You should be able to use a similar query with your data.
;WITH TheLatest AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY group-by-fields ORDER BY sorting-fields) AS ItemCount
FROM TheTable
)
SELECT *
FROM TheLatest
WHERE ItemCount = 1
UPDATE: I just noticed that this was tagged with sql-server-2000. This will only work on SQL Server 2005 and later.
Since you didn't give real table and field names, this is just psuedo code for a solution.
select *
from customer_table t2
inner join location_table t1
on t1.some_key = t2.some_key
where t1.LocationKey = (select top 1 (LocationKey) as LatestLocationKey from location_table where cust_id = t1.cust_id order by some_field)
Use an aggregate function in the query to group by customer IDs:
SELECT cust_Nbr, MAX(rec_alt_ts) AS most_recent_transaction, other_fields
FROM tableName
GROUP BY cust_Nbr, other_fields
ORDER BY cust_Nbr DESC;
This assumes that rec_alt_ts increases every time, thus the max entry for that cust_Nbr would be the most recent entry.
By using time and date we can take out the recent detail for the customer.
use the column from where you take out the date and the time for the customer.
eg:
SQL> select ename , to_date(hiredate,'dd-mm-yyyy hh24:mi:ss') from emp order by to_date(hiredate,'dd-mm-yyyy hh24:mi:ss');

Select values with duplicate max values sql

I have a table made up of dates and sales totals for the particular date. I would like to be able to query the table and select the following: max sales, the date associated with the max sale figure, sum of all sales, and the minimum date in the table. One additional complication is that there are duplicate max values. I don't care which max value is chosen but I just want one at random. This is for Oracle.
Here is what I tried. It was using a sub query.
Select sales, date, min(date), sum(sales) from table
Where sales = (select distinct(max(sales)) from table)
select
max(sales),
max(date_) keep (dense_rank first order by sales desc),
sum(sales),
min(date_)
from
table_
See also This SQL Fiddle