Share of invoiced in total (sum group by) - sql

I have sales lines some of them are invoiced, some not. I would like to add information of invoiced lines share per each order (salesid). I want this information for each sales line to be the same within one order. Invoiced line has sales status =3. Here's my try:
SELECT
salesid,linenum,itemid,salesstatus,name,lineamount
,(SELECT SUM(CASE WHEN salesstatus=3 THEN lineamount ELSE 0 END) as expr1) invoiced
,(SELECT SUM (lineamount) as expr2 GROUP BY salesid) total
,invoiced/total
FROM T.SALESLINES
GROUP BY
salesid,linenum,itemid,salesstatus,name,lineamount
Grouping by salesid does not work giving error "Each GROUP BY expression must contain at least one column that is not an outer reference."
I guess the code seems logical but does not work. So how should I group by salesid to divide invoiced by total?

try
Select *,invoiced/total as ColName from (
SELECT
salesid,linenum,itemid,salesstatus,name,lineamount
,(SELECT SUM(CASE WHEN salesstatus=3 THEN lineamount ELSE 0 END From T.SALESLINES) as invoiced
,(SELECT SUM (lineamount)From T.SALESLINES GROUP BY salesid) as total
FROM T.SALESLINES) source
GROUP BY
salesid,linenum,itemid,salesstatus,name,lineamount,invoiced,total

Related

How to get the asked columns for each customers

I have this table called table a
I need to get the CustomerID, sum(Income) of 2015, sum(Income) of 2016, did he ever bought productId A (boolean), is the total sum(income)> 1000 (boolean), number of total InvoiceID
all that in one query and the results should be with 1 row per customer.
please help I don't even know how to start!
This is basically conditional aggregation:
select customerid,
sum(case when extract(year from date) = 2015 then sales end) as sales_2015,
sum(case when extract(year from date) = 2016 then sales end) as sales_2016,
max( product = 'A' ) as ever_bought_a,
sum(income) > 1000 as sum_exceeds_1000,
count(*) as num_invoices
from t
group by customerid;
You haven't specified a database, so this is really psuedocode. You'll need to adapt it for your particular database.

Combine and fuse the results of two SQL queries with UNION

I am writing two seperate SQL queries to get data for two different dates like so:
SELECT number, sum(sales) as sales, sum(discount) sa discount, sum(margin) as margin
FROM table_a
WHERE day = '2019-08-09'
GROUP BY number
SELECT number, sum(sales) as sales, sum(discount) sa discount, sum(margin) as margin
FROM table_a
WHERE day = '2018-08-10'
GROUP BY number
I tried fusing them like so to get the results for the same number in one row from two different dates:
SELECT number, sum(sales) as sales, sum(discount) sa discount, sum(margin) as margin, 0 as sales_n1, 0 as discount_n1, 0 as margin_n1
FROM table_a
WHERE day = '2019-08-09'
GROUP BY number
UNION
SELECT number, 0 as sales, 0 as discount, 0 as margin, sum(sales_n1) as sales_n1, sum(discount_n1) as discount_n1, sum(margin_n1) as margin_n1
FROM table_a
WHERE day = '2018-08-10'
GROUP BY number
But it didn't work as I get the rows for the first query with zeroes for the columns defined as zero followed by the columns of the second query in the same fashion.
How can I correct this to have the desired output ?
Use conditional aggregation:
SELECT number,
sum(case when day = '2019-08-09' then sales end) as sales_20190809,
sum(case when day = '2019-08-09' then discount end) sa discount, sum(margin) as margin_20190810,
sum(case when day = '2019-08-10' then sales end) as sales_20190809,
sum(case when day = '2019-08-10' then discount end) sa discount, sum(margin) as margin_20190810
FROM table_a
WHERE day IN ('2019-08-09', '2019-08-10')
GROUP BY number;
If you want the numbers in different rows (which you don't seem to), then use aggregation:
SELECT day, number, sum(sales) as sales, sum(discount) as discount, sum(margin) as margin
FROM table_a
WHERE day IN ('2019-08-09', '2019-08-10')
GROUP BY day, number

How to get the last sold price in SQL

I am working on a query that will show me basic item information as well as the total qty shipped (for all orders),last date that the item was sold and the price it was sold at. I cant figure out how to get the last sold price. This is what I have so far,
SELECT
item_id
,item_desc
,sum(qty_shipped) AS 'Total Qty Shipped'
,count(item_id) AS 'No of times Shipped'
,max(invoice_date) AS 'Last Invoice_date'
,unit_price AS 'Last Price'
FROM sales_history_report
WHERE
item_id = '1234'
AND year_for_period >= '2017'
AND sales_location_id like '10'
GROUP BY
item_id
,item_desc
,unit_price
with this query I am getting all of the lines that this item is on. It looks like this right now,
Item_id,Item_desc,Total_QTY_shipped,no_of_times_shipped,Last_Invoice_date,Last_price
1234,Item 1234,4,1,2014-10-15,2.47
1234,Item 1234,6,1,2014-09-20,2.519
But I am looking for
Item_id,Item_desc,Total_QTY_shipped,no_of_times_shipped,Last_Invoice_date,Last_price
1234,Item 1234,10,2,2014-10-15,2.47
Any help would be appreciated.
If I understand correctly, you can use conditional aggregation:
select item_id, item_desc,
sum(qty_shipped) as [Total Qty Shipped],
count(item_id) as [No of times Shipped],
max(invoice_date) as Max_Date,
max(case when seqnum = 1 then unit_price end) as [Last Price],
from (select shr.*,
row_number() over (partition by item_id order by invoice_date desc) as seqnum
from sales_history_report shr
) shr
where item_id = 1234 and
year_for_period >= 2017 and
sales_location_id like '10'
group by item_id, item_desc;
Comments:
Do not use single quotes for column aliases. Only use single quotes for string and date constants.
The columns in the GROUP BY define the rows in the result set. I don't think you want unit_price in it.
Do not use single quotes for numeric constants. I assume item_id an the year are numeric.

Weighted-Avg Access Query

Background: I have the following table with clothing brand names, the count of the brand name sold, the revenue the brand name has brought in, and an avg per unit sold of that brand name.
Quantity Brand Revenue Rev_Per_Brand
1820 CMD $13,519.50 $7.43
791 ATL $8,997.00 $11.37
335 WHBM $4,988.00 $14.89
320 CH $4,593.50 $14.35
233 AT $3,207.50 $13.77
Objective: Calculate the weighted average revenue by quantity sold of brands.
What I Have Now:
SELECT
COUNT(*) AS [Quantity],
Sales.Description AS Brand,
FORMAT(SUM(Sales.Amt),"Currency") AS Revenue,
Format(SUM(Sales.Amt)/COUNT(*), "Currency") AS Rev_Per_Brand,
SUM(Sales.Amt)*(COUNT(*)/SUM(COUNT(*))) AS [wAvg_Rev_Per_Brand]
FROM Sales
WHERE Sales.Date > DateAdd("m",-1,NOW())
AND "This query lists brands that have sold in the past 1 month from today's date and returns the revenue received from them" <> ""
GROUP BY Sales.Description
ORDER BY COUNT(*) DESC;
Problem: I am receiving the cannot have aggregate function in expression error, and I am guessing it is probably in the SUM(COUNT(*)) part above.
I am simply trying to do the count of the specific brand over the total count (sum) of all brands sold. Can anyone tell me what I am doing wrong?
Thank you and I really appreciate any help in advance.
You can not double aggregate i.e SUM(COUNT(*)) you've got to have that count in a separate subquery,
change your query to:
SELECT
COUNT(*) AS [Quantity],
Sales.Description AS Brand,
FORMAT(SUM(Sales.Amt),"Currency") AS Revenue,
Format(SUM(Sales.Amt)/COUNT(*), "Currency") AS Rev_Per_Brand,
SUM(Sales.Amt)*(COUNT(*)/(SELECT Count(*) FROM sales)) AS [wAvg_Rev_Per_Brand]
FROM Sales
WHERE Sales.Date > DateAdd("m",-1,NOW())
AND "This query lists brands that have sold in the past 1 month from today's date and returns the revenue received from them" <> ""
GROUP BY Sales.Description
ORDER BY COUNT(*) DESC;

Working out total from sub total and amount

I have a table with purchased orders data.
Each row contails the amount of certain item purchased, cost per item and the order number group. Each different item purchased is a new row with same order number.
I basically want to return the total cost for that order. I have tried the following but am getting nowhere:
SELECT order_number, SUM( sub_total ) AS `total`
FROM
SELECT order_number, SUM( SUM( amount ) * SUM( cost_per_item ) ) AS `sub_total`
FROM `ecom_orders`
WHERE member_id = '4'
GROUP BY order_number
ORDER BY purchase_date DESC
Pretty much any SQL-92 compliant RDBMS will take this:
SELECT
order_number
,SUM(amount * cost_per_item) AS total
,purchase_date
FROM
ecom_orders
WHERE member_id = '4'
GROUP BY order_number,purchase_date
ORDER BY purchase_date DESC