SQL Custom Grouping and Selection Query - sql

I recently asked this question here and got some great answers!
Custom SQL GROUP BY Clause
However, it turns out I provided the wrong requirements for my problem. Sorry guys!
Sooooo. What I need to select is:
Distinct values in the Column 'PartNumbers', however:
-->For EACH unique PartNumber, I want to select the specific ROW from that table that has the MAX VALUE of the 'PO' Column for that particular part number.
-->Also, to make life more difficult, I want to exclude the ANY of the PartNumbers who have ANY VALUE in the Column 'Receipt'
You guys have been a great help! Much appreciated everyone!
EDIT:
Table Name: Log
Columns: ID, Supplier, PartNumber, PO, Quantity, DateReceived
Note: only the ID column is unique.

Using CTE:
with TableWithRowNumber as
(select
*,
row_number() over (partition by PartNumber order by PO desc) as RowNo
from MyTable)
select * from TableWithRowNumber
where RowNo = 1
and PartNumber not in
(select distinct PartNumber from MyTable where Receipt is not null)

Related

Sum amount group by id in temporary table

This is my code:
SELECT ROW_NUMBER()OVER(order by date) as rowNo, id, amount
INTO #temptbl
FROM sales
WHERE code = 1000
I'm trying to group this temporary table and sum the amount by its id so the id will be unique.
*The row column is mandatory because it will be used later.
I've tried few ways like this,
SELECT ROW_NUMBER()OVER(order by date) as rowNo, id, amount
INTO #temptbl
FROM sales
WHERE code = 1000
GROUP BY id
and even tried subquey nad nesting but it wont work. I know the solution must be simple its just i cant see it yet. Thank you
You can use SUM with Partition BY like this:
SELECT ROW_NUMBER()OVER(order by date) as rowNo, id,
Sum(amount) over (partition by id) sumAmount
FROM sales
WHERE code = 1000
As you know, since you want the Row number then sum amount will be repeated for same ids

how to get latest date column records when result should be filtered with unique column name in sql?

I have table as below:
I want write a sql query to get output as below:
the query should select all the records from the table but, when multiple records have same Id column value then it should take only one record having latest Date.
E.g., Here Rudolf id 1211 is present three times in input---in output only one Rudolf record having date 06-12-2010 is selected. same thing with James.
I tried to write a query but it was not succssful. So, please help me to form a query string in sql.
Thanks in advance
You can partition your data over Date Desc and get the first row of each partition
SELECT A.Id, A.Name, A.Place, A.Date FROM (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Date DESC) AS rn
FROM [Table]
) A WHERE A.rn = 1
you can use WITH TIES
select top 1 PERCENT WITH TIES * from t
order by (row_number() over(partition by id order by date desc))
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=280b7412b5c0c04c208f2914b44c7ce3
As i can see from your example, duplicate rows differ only in Date. If it's a case, then simple GROUP BY with MAX aggregate function will do the job for you.
SELECT Id, Name, Place, MAX(Date)
FROM [TABLE_NAME]
GROUP BY Id, Name, Place
Here is working example: http://sqlfiddle.com/#!18/7025e/2

Finding the maximum price for a given customer id

I need to write a hive query. I am working on a data set that has three columns : Customer ID, Product ID and the Price. I need to write a query which outputs the columns Customer ID and Product ID for the maximum item bought by the customer.
SELECT [customer], [product] FROM table WHERE [price] = (SELECT MAX(t.[price]) AS price
FROM table as t WHERE t.[customer] = [customer])
Could be something like this if you're wanting to find the most expensive item that a customer has purchased? I'm unsure if the syntax is 100% correct but it should give you something to go from. I've added a cheat sheet below for Hive just incase.
Hive Cheat Sheet
Using row_number():
select Customer_ID, Product_ID
from
(select Customer_ID,
Product_ID,
row_number () over ( partition by Customer_ID order by Price desc) rn
from table
where customer_id=given_customer_id --add filter if necessary
)s
where rn=1;

Max of a Date field into another field in Postgresql

I have a postgresql table wherein I have few fields such as id and date. I need to find the max date for that id and show the same into a new field for all the ids. SQLFiddle site was not responding so I have an example in the excel. Here is the screenshot of the data and the output for the table.
You could use the windowing variant of max:
SELECT id, date, MAX(date) OVER (PARTITION BY id)
FROM mytable
Something like this might work:
WITH maxdts AS (
SELECT id, max(dt) maxdt FROM table GROUP BY id
)
SELECT id, date, maxdt FROM table t, maxdts m WHERE t.id = m.id;
Keep in mind without more information that this could be a horribly inefficient query, but it will get you what you need.

Fastest/most efficient way to perform this SQL Server 2008 query?

I have a table which contains:
-an ID for a financial instrument
-the price
-the date the price was recorded
-the actual time the price was recorded
-the source of the price
I want to get the index ID, the latest price, price source and the date of this latest price, for each instrument, where the source is either "L" or "R". I prefer source "L" to "R", but the latest price is more important (so if the latest price date only has a source of "R"- take this, but if for the latest date we have both, take "L").
This is the SQL I have:
SELECT tab1.IndexID, tab1.QuoteDate, tab2.Source, tab2.ActualTime FROM
(SELECT IndexID, Max(QuoteDate) as QuoteDate FROM PricesTable GROUP BY IndexID) tab1
JOIN
(SELECT IndexID, Min(Source) AS Source, Max(UpdatedTime) AS ActualTime, QuoteDate FROM PricesTable WHERE Source IN ('L','R') GROUP BY IndexID, QuoteDate) tab2
ON tab1.IndexID = tab2.IndexID AND tab1.QuoteDate = tab2.QuoteDate
However, I also want to extract the price field but cannot get this due to the GROUP BY clause. I cannot extract the price without including price in either the GROUP BY, or an aggregate function.
Instead, I have had to join the above SQL code to another piece of SQL which just gets the prices and index IDs and joins on the index ID.
Is there a faster way of performing this query?
EDIT: thanks for the replies so far. Would it be possible to have some advice on which are more efficient in terms of performance?
Thanks
Use ROW_NUMBER within a subquery or CTE to order the rows how you're interested in them, then just select the rows that come at the top of that ordering. (Use PARITION so that row numbers are reaassigned starting at 1 for each IndexId):
;WITH OrderedValues as (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY IndexID ORDER BY QuoteDate desc,Source asc) as rn
FROM
PricesTable
)
SELECT * from OrderedValues where rn=1
Try:
select * from
(select p.*,
row_number() over (partition by IndexID
order by QuoteDate desc, Source) rn
from PricesTable p
where Source IN ('L','R')
) sq
where rn = 1
(This syntax should work in relatively recent versions of Oracle, SQLServer or PostgreSQL, but won't work in MySQL.)