How to Sum up fields across different groups in T-SQL - 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.

Related

Find Nearest rows in 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.

SQL grouping with multiple rows

There's a table that I use that lists invoice detail. So for instance let's say a customer checks out with 2 items, there are 2 rows for each item.
Right now my SQL Query looks like this:
Select date
,order_id
,count(distinct(item_name))
from Table_1
group by 1,2
Rather than grouping it by order_id. Is there anyway to modify this query to find the number of Orders that have X amount of items on a specific date. So on 1/1/1990 5 orders have 3 items, 6 orders have 2 items, etc.
Thanks for the help!
If I'm understanding your question correctly, you could use a subquery grouping by the item count:
select t.date, t.itemCount, t.count(order_id)
from (
Select date
,order_id
,count(distinct(item_name)) AS itemCount
from Table_1
group by 1,2
) AS t
group by date, itemCount

Grab ordered records grouped by ID where the first record of that group == 10

Using W3 Schools SQL Server Query Tool I remove the contents and enter the following:
SELECT * FROM OrderDetails
ORDER BY ProductID, Quantity;
And click Run SQL. It nicely orders by the ProductID and then for tie breakers on ProductID It orders by Quantity.
Here is what I want to do. With the table ordered as above: I want to group together the ProductID's on this table, and then return only those ProductID groups where the first record of each group's Quantity amount is == 10.
I attempted something like this but it doesn't work:
SELECT * FROM OrderDetails
ORDER BY ProductID, Quantity
Group By ProductID
Having first(Quantity == 10);
If I read this correctly, you want all the products that have 10 as the smallest quantity that has been ordered in productId order.
SELECT productId, min(quantity) as first FROM OrderDetails
group by productId
having first = 10
ORDER BY ProductID
EDIT to answer comment below.
The same logic will work with a string column. In this example, I'm showing all suppliers where the first product (with products listed alphabetically) starts with a C (try it in the W3 query tool). If I had data that any repeating string data, I could have done an =.
SELECT supplierId, min(productName) as first from products
group by supplierId
having first like 'C%'
order by supplierId

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)

SQL Server query to further summarize grouped data

Assume a table named transactions with two columns: invoiceNumber and itemNumber. Multiple quantities of an item on a single invoice are reflected by multiple records in the table. (I know this isn't an appropriate design, but I'm simplifying a more complex structure to get at the root question.)
I can determine the average number of unique items for each invoice with a query like:
SELECT invoiceNumber, COUNT(DISTINCT itemNumber)
FROM transactions
GROUP BY invoiceNumber
This query effectively ignores the quantity of an item, counting each one only once per invoice and shows the result for each invoice.
Instead of all this detailed information, however, all I really want is to determine the average number of unique items across all invoices. That is, I just want to summarize the per-invoice information. How do I do that?
You can aggregate the result you've already figured out how to obtain.
WITH DistinctCounts AS (
SELECT invoiceNumber, COUNT(DISTINCT itemNumber) AS distinctItems
FROM transactions
GROUP BY invoiceNumber
)
SELECT AVG(distinctItems)
FROM DistinctCounts
Select avg(numberininvoice)
From
(
Select invoicenumber, count(itemnumber) as numberininvoie
From
(Select distinct invoicenumber, itemnumber
From transactions) a
Group by invoicenumber
) b