need help in sql

Farhan Jamil 421 Reputation points
2021-12-23T15:24:37.19+00:00

Hey Guys

I need help here. Please see attached. I want revenue column in my sql query. I am unable to get it . The way to calculate revenue column is retailsales/sum(retailsales). Also the one attached is a derived table from different sources.

160133-image.png

My SQL so far which calculates till retail sales is as follows:-

select cast(h.StartDateTime as date) as TxnDate,b.code as BranchCode,b.name as BranchName,p.code as SKU,p.name as SKU_Description, i.LineValue as SalesValue, i.Quantity as Quantity
into #wtd_sales
from Txn.Header h
join dbo.vw_branch b on h.fkBranchId = b.pkBranchID
join txn.ItemLine i on i.fkHeaderId = h.pkHeaderId
join ProductVariant pv on pv.pkProductVariantID = i.fkProductVariantId
join product p on p.pkProductID = pv.fkProductID
where cast(h.startdatetime as date) =cast(getdate()-1 as date) and b.code in(853)

select SKU,SKU_Description,sum(Quantity) as Quantity,sum(SalesValue) as Retailsales
,row_number() over(order by sum(quantity) desc)as r
into #wtd_bd
from #wtd_sales
group by sku,SKU_Description

/Not sure whether this approach is correct to calculate revenue as seen in the screenshot/

select sku,sku_description,Quantity,sum(Retailsales) over(order by r asc) as Total
from #wtd_bd
where r between 1 and 25

any help will be much appreciated

Farhan Jamil

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
{count} votes

Answer accepted by question author
  1. Tom Cooper 8,496 Reputation points
    2021-12-23T16:11:38.603+00:00

    I think you want

    Select sku, sku_description, Quantity, Retailsales,
      Retailsales / Sum(RetailSales) Over () As Revenue
    From wtd_bd;
    

    Tom

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.