Find Nearest rows in SQL - sql

I have table with 2 records and column name quantity.
quantity
2268
22680
so,
when my required quantity 2500 then i want to display both 2 records
when my required quantity 2000 then display 1st row.

You seem to want a cumulative sum. The ANSI standard method would be:
select t.*
from (select t.*, sum(quantity) over (order by ?) as cume_quantity
from t
) t
where cume_quantity - quantity <= <your value here>;
The ? is for the column or expression that specifies the ordering of the rows.

Related

How could I get the maximun value on a field on SQL Server without max?

I need to get the max value on a field of a table but I can't use max or any other aggregation function nor cursors. For example I need to get the max value of the field amount on the table Sales.
A couple of ways:
1. Sort the column descending and get the 1st row:
select top 1 amount from sales order by amount DESC
2. With NOT EXISTS:
select distinct s.amount
from sales s
where not exists (
select 1 from sales
where amount > s.amount
)

multiply the no of column values in sql

i am having a column name as amount in a table . in that 5 amounts are there, i need to calculate the amount of values in 5 rows , those 5 rows amount need to be added and need to show in a single column as a total amount
You can do it with a simple SUM() function and specify it as a new column with the AS Alias like this:
SELECT SUM(amount) AS totalAmount FROM TableName;
This will give you a new column as total of amounts.
And if you want to show other columns and the total amount column in the end you can do it using nested queries:
SELECT *, (SELECT SUM(amount) FROM TableName) AS totalAmount FROM TableName;

Sum values from one column if Index column is distinct?

How do I sum values from one column when index column is distinct?
Initially, I had this SQL query:
SELECT COALESCE(SUM(ISNULL(cast(Quantity as int),0)),0) AS QuantitySum FROM Records
Also tried to do this, but this is incorrect when some Quantity values happen to be the same:
SELECT COALESCE(SUM(DISTINCT ISNULL(cast(Quantity as int),0)),0) AS QuantitySum FROM Records
How can I fix this query to sum only records quantity that is distinct by Index value?
Example of Table:
Index Quantity
AN121 40
AN121 40
BN222 120
BN111 20
BN2333 40
So.. I want to return 220
I have duplicate Ids, but quantity can be the same for different records
Do you mean that you only want to sum one value of quantity for each individual value of the index column?
select sum(case when row_number() over (partition by `index` order by newid()) = 1
then cast(Quantity as int)
end) as QuantitySum
from Records;
Or, do you mean that you only want to sum values of quantity when there is exactly one row with a given index value:
select sum(case when count(*) over (partition by `index`) = 1
then cast(Quantity as int)
end) as QuantitySum
from Records;
Both of these use window functions to restrict the values being processed.
Also, a column called quantity should be stored as a numeric type, so conversion isn't needed to take the sum.
You can try something like:
SELECT DISTINCT COL1
, SUM(COL2)
FROM MYTABLE
GROUP BY COL1
You can use this, if you have duplicated Ids and Quantity:
SELECT COALESCE(SUM(DISTINCT ISNULL(cast(Quantity as int),0)),0) AS QuantitySum
FROM (SELECT Id, Min(Quantity) From Records group by Id)

Return min date and corresponding amount to that distinct ID

Afternoon
I am trying to return the min value/ max values in SQL Server 2005 when I have multiple dates that are the same but the values in the Owed column are all different. I've already filtered the table down by my select statement into a temp table for a different query, when I've then tried to mirror I have all the duplicated dates that you can see below.
I now have a table that looks like:
ID| Date |Owes
-----------------
1 20110901 89
1 20110901 179
1 20110901 101
1 20110901 197
1 20110901 510
2 20111001 10
2 20111001 211
2 20111001 214
2 20111001 669
My current query:
Drop Table #Temp
Select Distinct Convert(Varchar(8), DateAdd(dd, Datediff(DD,0,DateDue),0),112)as Date
,ID
,Paid
Into #Temp
From Table
Where Paid <> '0'
Select ,Id
,Date
,Max(Owed)
,Min(Owed)
From #Temp
Group by ID, Date, Paid
Order By ID, Date, Paid
This doesn't strip out any of my dates that are the same, I'm new to SQL but I'm presuming its because my owed column has different values. I basically want to be able to pull back the first record as this will always be my minimum paid and my last record will always be my maximum owed to work out my total owed by ID.
I'm new to SQL so would like to understand what I've done wrong for my future knowledge of structuring queries?
Many Thanks
In your "select into"statement, you don't have an Owed column?
GROUP BY is the normal way you "strip out values that are the same". If you group by ID and Date, you will get one row in your result for each distinct pair of values in those two columns. Each row in the results represents ALL the rows in the underlying table, and aggregate functions like MIN, MAX, etc. can pull out values.
SELECT id, date, MAX(owes) as MaxOwes, MIN(owes) as minOwes
FROM myFavoriteTable
GROUP BY id, date
In SQL Server 2005 there are "windowing functions" that allow you to use aggregate functions on groups of records, without grouping. An example below. You will get one row for each row in the table:
SELECT id, date, owes,
MAX(Owes) over (PARTITION BY select, id) AS MaxOwes,
MIN(Owes) over (PARTITION BY select, id) AS MinOwes
FROM myfavoriteTable
If you name a column "MinOwes" it might sound like you're just fishing tho.
If you want to group by date you can't also group by ID, too, because ID is probably unique. Try:
Select ,Date
,Min(Owed) AS min_date
,Max(Owed) AS max_date
From #Temp
Group by Date
Order By Date
To get additional values from the row (your question is a bit vague there), you could utilize window functions:
SELECT DISTINCT
,Date
,first_value(ID) OVER (PARTITION BY Date ORDER BY Owed) AS min_owed_ID
,last_value(ID) OVER (PARTITION BY Date ORDER BY Owed) AS max_owed_ID
,first_value(Owed) OVER (PARTITION BY Date ORDER BY Owed) AS min_owed
,last_value(Owed) OVER (PARTITION BY Date ORDER BY Owed) AS max_owed
FROM #Temp
ORDER BY Date;

How to Sum up fields across different groups in T-SQL

I have a bunch of tables that I left join and a Group By clause that groups a bunch of columns.
However, there is a one column that is group-by'ed on but remains distinct (productNumber).
I need to sum up the quantity column below:
salesID historyID productID name productNumber quantity
1 123 1 A 234554 10
1 123 1 A 666666 10
I want only the first record but with the quantity of 10+10=20.
The first record would have a flag mainNumber = 1 and the second record would have a mainNumber=0, however that column does not appear in the SELECT.
In other words, I'd like to sum up the quantities but only display the productNumber where mainNumber=1.
How do I do that?
Thanks!
If I understood the question correctly, this may help you:
SELECT salesID, historyID, productID, name, productNumber, total.quantity
FROM table1
JOIN (
SELECT salesID, SUM(quantity) AS quantity FROM table1 GROUP BY salesID
) AS total
ON table1.salesID = total.salesID
WHERE mainNumber=1
Not totally sure I understood... In the result set you want only the first row but which value should be in the productNumber column?
If just about any value would do, you must not GROUP BY productNumber (which keeps the rows distinct) but aggregate it, e.g. with MIN or MAX.