I need a query for [Contribution]. I used this query:
with ttt as
(
select
(DYG.U_StyleId)[DYG Style]
,Max(O1.CardCode) [Party Group Code],
MAX(O1.CardName) [Party Group Name]
,MAX(OR1.DocDate) [Date]
,sum(CONVERT(NUMERIC(15,2),(RDR1.PriceBefDi*RDR1.Quantity))) [JobAmount]
,CONVERT(NUMERIC(15,2),SUM(RDR1.Quantity)) [Mtr]
,CONVERT(NUMERIC(15,2),SUM(RDR1.U_Pcs))[Pcs]
,(select sum(RDR1.PriceBefDi*RDR1.Quantity) from RDR1) tqty
from
ORDR OR1
left join RDR1 on RDR1.DocEntry = OR1.DocEntry
left join OITM on RDR1.ItemCode = oitm.ItemCode
LEFT JOIN OCRD ON OCRD.CardCode = OR1.CardCode
LEFT JOIN OCRG ON OCRG.GroupCode = OCRD.GroupCode
LEFT JOIN OCRD O1 ON O1.U_BCode = OCRD.U_GrpCod
LEFT JOIN
( SELECT U_StyleId FROM RDR1 WHERE U_StyleId in
('BLOOM','BLOOMING','DYD','DYD-R','DYED','Ex.CLR.','RAINBOW'))
DYG ON DYG.U_StyleId = RDR1.U_StyleId
group by
DYG.U_StyleId
)
select
Style, [Party Group Code],
[Party Group Name], JobAmount,
(sum(JobAmount) / tqty * 100) [Contribution],
[Date], [Pcs]
from
ttt
group by
Style
I need Sum of last jobamount to divide it with above tqty.
But it shows this error.
'Column 'ttt.Party Group Code' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.'
Please help me with the query to get right [Contribution] amount.
Try this:
select Style,[Party Group Code],[Party Group Name],JobAmount,[Date],[Pcs],
100.0 * (sum(JobAmount) OVER (PARTITION BY Style))/tqty [Contribution]
from ttt;
Related
I have a sp as following to get a list of areacode(phone) and sales amount on a selected percentile. For example at 0.5. However, I don't only want to see the data at 0.5,I also want to see the data above 0.5(the selected parameter).How can I do with sql server coding?
CREATE PROCEDURE USP_Percentile1 #per real
AS
SELECT c.[area code],PERCENTILE_DISC(#per) WITHIN GROUP (ORDER BY SalesAmount) OVER (PARTITION BY [area code]) AS percentileamount
from (select SUBSTRING(s.phone,2,3) as [area code],sum(b.Salesamount) as SalesAmount from Orders a
join (select OrderID, sum(UnitPrice * Quantity * (1-Discount) ) as Salesamount from [Order Details] group by OrderID) as b
on a.OrderID = b.OrderID
join Shippers s
on a.ShipVia=s.ShipperID
group by s.Phone) c
exec SP_1 0.5
You can use the PERCENT_RANK function for this. Place it inside the subquery and filter it afterwards.
You should make good use of whitespace and formatting, it's free.
Also, see Bad Habits to Kick : Using table aliases like (a, b, c) or (t1, t2, t3)
CREATE PROCEDURE USP_Percentile1 #per real
AS
SELECT
o.[area code],
percentileamount
from (
select
SUBSTRING(s.phone, 2, 3) as [area code],
sum(od.Salesamount) as SalesAmount,
PERCENTILE_DISC(#per) WITHIN GROUP (ORDER BY sum(od.Salesamount)) OVER (PARTITION BY [area code]) AS percentileamount,
PERCENT_RANK() OVER (PARTITION BY [area code] ORDER BY sum(od.Salesamount)) AS percentile
from Orders o
join (
select
OrderID,
sum(UnitPrice * Quantity * (1-Discount) ) as Salesamount
from [Order Details]
group by OrderID
) as od on o.OrderID = od.OrderID
join Shippers s on o.ShipVia = s.ShipperID
group by s.Phone
) o
where
o.percentile >= #per;
My current query returns too many lines per Subject_ID, so I want to use ROW_NUMBER() to limit the resulting set to 1 line per Subject_ID. I've added this line to my SELECT statement:
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
But when I try to put WHERE rn = 1 anywhere in the FROM statement, I get the error:
Incorrect syntax near the keyword 'WHERE'
And when I try to change it to AND rn = 1 (and add it on to another AND/OR line) I get the error:
Invalid column name 'rn'
So my first question is: When I add a field to my SELECT statement using that ROW_NUMBER() line, what table does this column belong to? Do I need to append it to something like Table.rn? My second question is where should I put this rn = 1 line and how should I write it in?
Full query:
SELECT
Groups.Group_Name
, CT.Created
, CT.Subject_Id
INTO #temp
FROM SubjectZ_Task CT
INNER JOIN
SubjectZ_Task_Users On CT.SubjectZ_Task_Id = SubjectZ_Task_Users.SubjectZ_Task_Id
INNER JOIN
Groups ON Groups.Group_ID = SubjectZ_Task_Users.Group_Reference
WHERE Group_Name LIKE 'Team 1'
AND CT.Created >= '1/1/2019' AND CT.Created < DATEADD(Day,1,'12/31/2019')
GROUP BY Groups.group_name, CT.Created, CT.Subject_ID
SELECT
CT.Group_Name
, CT.Created
, CS.Topic_Start_Date
, CS.Subject_ID
, P.FirstName
, P.LastName
, CS.Subject_Match_ID
, SubjectX.Firstname AS SubjectX_firstname
, CS.SubjectY
, AEC.AEC AS Max_AEC
, SubjectX.Email_id As SubjectX_Email
, Phone.Phone
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
FROM #temp CT
LEFT JOIN QE_Topic_Summary CS ON CS.Subject_ID = CT.Subject_Id
AND (Topic_Status LIKE 'In Progress'
OR Topic_Status LIKE 'Pending')
AND CS.Topic_Start_Date >= DATEADD(Day,-60,CT.Created) AND CS.Topic_Start_Date <= DATEADD(Day,60,CT.Created)
INNER JOIN Subjects P ON P.Subject_ID = CS.Subject_ID
LEFT JOIN Subjects SubjectX ON SubjectX.Subject_ID = CS.SubjectX_ID
LEFT JOIN QE_TB_MAX_AEC AEC ON AEC.Subject_ID = CS.Subject_ID
INNER JOIN Subject_Identifiers PI ON PI.Subject_ID = P.Subject_ID
LEFT JOIN Subject_Identifiers PIP ON PIP.Subject_ID = SubjectX.Subject_ID
LEFT JOIN Subject_Phone Phone On Phone.Subject_ID = P.Subject_ID WHERE Phone.Voice = 1
drop table #temp
I don't see a reference to rn in your WHERE clause, but my guess is that you need to wrap it in another query like so:
SELECT *
FROM(
SELECT
CT.Group_Name
, CT.Created
, CS.Topic_Start_Date
, CS.Subject_ID
, P.FirstName
, P.LastName
, CS.Subject_Match_ID
, SubjectX.Firstname AS SubjectX_firstname
, CS.SubjectY
, AEC.AEC AS Max_AEC
, SubjectX.Email_id As SubjectX_Email
, Phone.Phone
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
FROM #temp CT
LEFT JOIN QE_Topic_Summary CS ON CS.Subject_ID = CT.Subject_Id
AND (Topic_Status LIKE 'In Progress'
OR Topic_Status LIKE 'Pending')
AND CS.Topic_Start_Date >= DATEADD(Day,-60,CT.Created) AND CS.Topic_Start_Date <= DATEADD(Day,60,CT.Created)
INNER JOIN Subjects P ON P.Subject_ID = CS.Subject_ID
LEFT JOIN Subjects SubjectX ON SubjectX.Subject_ID = CS.SubjectX_ID
LEFT JOIN QE_TB_MAX_AEC AEC ON AEC.Subject_ID = CS.Subject_ID
INNER JOIN Subject_Identifiers PI ON PI.Subject_ID = P.Subject_ID
LEFT JOIN Subject_Identifiers PIP ON PIP.Subject_ID = SubjectX.Subject_ID
LEFT JOIN Subject_Phone Phone On Phone.Subject_ID = P.Subject_ID
WHERE Phone.Voice = 1
)t
WHERE t.rn = 1
I'm trying to calculate list all Customers A/C Receivables.
I calculate list of sales and receipts of customers, now I'm stuck how to calculate Receivables.
All Customer's Sales Report
Select c.StakeHolderId, c.CompanyName, sum(s.Amount) as TotalSales from
StakeHolders c
left Join Sales s on
c.StakeHolderId = s.BuyerId
where c.StakeHolderTypeId = '0b85a69e-55f2-4142-a49d-98e22aa7ca10'
group By c.StakeHolderId, c.CompanyName
All Customer's Receipts
Select c.StakeHolderId, c.CompanyName, sum(pr.Amount) as TotalReceipts
from
StakeHolders c
left Join PaymentsAndReceipts pr on
c.StakeHolderId = pr.StakeHolderId
where c.StakeHolderTypeId = '0b85a69e-55f2-4142-a49d-98e22aa7ca10'
group By c.StakeHolderId, c.CompanyName
I have tried this but didn't get the right result.
Select
c.StakeHolderId,
c.CompanyName,
sum(s.Amount) - sum(pr.Amount) as Receivables
from Sales s
right outer join StakeHolders c on
c.StakeHolderId = s.BuyerId
left outer join PaymentsAndReceipts pr on
pr.StakeHolderId = c.StakeHolderId
where c.StakeHolderTypeId = '0b85a69e-55f2-4142-a49d-98e22aa7ca10'
Group By c.StakeHolderId,c.CompanyName
expected Result:
Does this work for you?:
WITH [CalculatedData] AS
(
SELECT
C.[StakeHolderId],
C.[CompanyName],
COALESCE((SELECT SUM([Amount])
FROM [Sales]
WHERE [BuyerId] = C.[StakeHolderId]
), 0) AS [TotalSales],
COALESCE((SELECT SUM([Amount])
FROM [PaymentsAndReceipts]
WHERE [StakeHolderId] = C.[StakeHolderId]
), 0) AS [TotalReceipts]
FROM
[StakeHolders] AS C
WHERE
C.[StakeHolderTypeId] = '0b85a69e-55f2-4142-a49d-98e22aa7ca10'
)
SELECT
[StakeHolderId],
[CompanyName],
[TotalSales] - [TotalReceipts] AS [Receivables]
FROM
[CalculatedData]
Note that I include negative values in the result. If you want negative values shown between parentheses, that's possible too, but it will require conversion of numerical data to textual data in the query results. IMHO, that's not a flexible strategy (since you lose the option to perform any additional client-side calculations) and it should be the client's purpose to correctly format the values.
Edit:
If you don't like Common Table Expressions, you can convert it to a regular table expression:
SELECT
[StakeHolderId],
[CompanyName],
[TotalSales] - [TotalReceipts] AS [Receivables]
FROM
(
SELECT
C.[StakeHolderId],
C.[CompanyName],
COALESCE((SELECT SUM([Amount])
FROM [Sales]
WHERE [BuyerId] = C.[StakeHolderId]
), 0) AS [TotalSales],
COALESCE((SELECT SUM([Amount])
FROM [PaymentsAndReceipts]
WHERE [StakeHolderId] = C.[StakeHolderId]
), 0) AS [TotalReceipts]
FROM
[StakeHolders] AS C
WHERE
C.[StakeHolderTypeId] = '0b85a69e-55f2-4142-a49d-98e22aa7ca10'
) AS [CalculatedData]
just take first query LEFT JOIN to second query join by StakeHolderId & companyname. After that take sales subtract receipts
SELECT S.StakeHolderId, S.CompanyName,
Receivables = TotalSales - ISNULL(TotalReceipts , 0)
FROM
(
-- this is your first query
Select c.StakeHolderId, c.CompanyName, sum(s.Amount) as TotalSales from
StakeHolders c
left Join Sales s on
c.StakeHolderId = s.BuyerId
where c.StakeHolderTypeId = '0b85a69e-55f2-4142-a49d-98e22aa7ca10'
group By c.StakeHolderId, c.CompanyName
) S
LEFT JOIN
(
-- this is your second query
Select c.StakeHolderId, c.CompanyName, sum(pr.Amount) as TotalReceipts
from
StakeHolders c
left Join PaymentsAndReceipts pr on
c.StakeHolderId = pr.StakeHolderId
where c.StakeHolderTypeId = '0b85a69e-55f2-4142-a49d-98e22aa7ca10'
group By c.StakeHolderId, c.CompanyName
) R ON S.StakeHolderId = R.StakeHolderId
AND S.CompanyName = R.CompanyName
I need help with this. I have this SQL statement:
ALTER proc [dbo].[GetDSR]
(
#WholeSellerId varchar(50),
#FromDate date
)
as
begin
with cte1 as
(select co.ProductId as copid, co.DateAdded as coda, sum(isnull(co.quantity,0)) as coq, co.WholeSellerId as coid
from ConsignmentSale co
group by co.ProductId, co.DateAdded, co.WholeSellerId),
cte2 as
(select ca.ProductId as caid, sum(isnull(ca.quantity,0)) as caq from CashSale ca
group by ca.ProductId),
cte3 as
(select wi.ProductId as wiid, sum(isnull(wi.Quantity,0)) as wiq from Withdrawal wi
group by wi.ProductId),
cte4 as
(select po.ProductId as poid, sum(isnull(po.Quantity,0)) as poq from Pullout po
group by po.ProductId),
cte5 as
(select pr.ProductId as prid, sum(isnull(pr.Quantity,0)) as prq from Promotion pr
group by pr.ProductId)
select cte1.copid as Product, cte1.coda, isnull(cte1.coq,0) as Credit, isnull(cte2.caq,0) as Cash,
isnull(cte3.wiq,0) as Withdrawal, isnull(cte4.poq,0) as Pullout, isnull(cte5.prq,0) as Promotion
from cte1
full outer join cte2 on cte2.caid=cte1.copid
full outer join cte3 on cte3.wiid=cte1.copid
full outer join cte4 on cte4.poid=cte1.copid
full outer join cte5 on cte5.prid=cte1.copid
where cte1.coid = #WholeSellerId and cte1.coda = #FromDate
end
go
It gives me the right result only when there is a data in the ConsignmentSale that meets the specific condition. The problem is, when there is no data in the ConsignmentSale that meets the condition but there is in some other table, it is not displayed. Probably it is because of this part:
where cte1.coid = #WholeSellerId and cte1.coda = #FromDate
It is only using the criteria in a single table, the ConsignmentSale, and it does not check the rest of the table for this criteria. Please show me how to alter this procedure in such a way that even if in the ConsignmentSale the criteria is not met but in the other table it is met, it will still give me result and the coq is just going to be 0 since it does not have data that adheres to that criteria.
Thank you.
Move the filter's to ON condition
................
FROM cte1
FULL OUTER JOIN cte2
ON cte2.caid = cte1.copid
AND cte1.coid = #WholeSellerId
AND cte1.coda = #FromDate
FULL OUTER JOIN cte3
ON cte3.wiid = cte1.copid
FULL OUTER JOIN cte4
ON cte4.poid = cte1.copid
FULL OUTER JOIN cte5
ON cte5.prid = cte1.copid
.................
I just created a criteria on each statement like so:
ALTER proc [dbo].[GetDSR]
(
#WholeSellerId varchar(50),
#FromDate date
)
as
begin
with
cte1 as
(select pr.ProductId from Product pr),
cte2 as
(select co.WholeSellerId as cowi, co.DateAdded as coda, co.ProductId as coid, sum(isnull(co.Quantity,0)) as coq from ConsignmentSale co
where co.WholeSellerId=#WholeSellerId and co.DateAdded=#FromDate
group by co.ProductId, co.DateAdded, co.WholeSellerId),
cte3 as
(select ca.DateAdded as cada, ca.WholeSellerId as cawi, ca.ProductId as caid, sum(isnull(ca.Quantity,0)) as caq from CashSale ca
where ca.WholeSellerId=#WholeSellerId and ca.DateAdded=#FromDate
group by ca.ProductId, ca.WholeSellerId, ca.DateAdded),
cte4 as
(select pm.DateAdded as pmda, pm.ProductId as pmid, pm.WholeSellerId as pmwi, sum(isnull(pm.Quantity,0)) as pmq from Promotion pm
where pm.WholeSellerId=#WholeSellerId and pm.DateAdded=#FromDate
group by pm.DateAdded, pm.ProductId, pm.WholeSellerId),
cte5 as
(select wi.ProductId as wiid, wi.DateAdded as wida, wi.WholeSellerId as wiwi, sum(isnull(wi.Quantity,0)) as wiq from Withdrawal wi
where wi.WholeSellerId=#WholeSellerId and wi.DateAdded=#FromDate
group by wi.DateAdded, wi.WholeSellerId, wi.ProductId),
cte6 as
(select po.ProductId as poid, po.DateAdded as poda, po.WholeSellerId as powi, sum(isnull(po.Quantity,0)) as poq from Pullout po
where po.WholeSellerId=#WholeSellerId and po.DateAdded=#FromDate
group by po.ProductId, po.DateAdded, po.WholeSellerId)
select cte1.ProductId as 'Product', isnull(cte2.coq,0) as 'Credit', isnull(cte3.caq,0) as 'Cash', isnull(cte5.wiq,0) as 'Withdrawal',
isnull(cte6.poq,0) as 'Pullout', isnull(cte4.pmq,0) as 'Promotion'
from cte1
full outer join cte2 on cte2.coid = cte1.ProductId
full outer join cte3 on cte3.caid=cte1.ProductId
full outer join cte4 on cte4.pmid=cte1.ProductId
full outer join cte5 on cte5.wiid=cte1.ProductId
full outer join cte6 on cte6.poid=cte1.ProductId
end
I am learning window functions in sql server. I am using AdventrueWorks2012 database for practice. I want to calculate total number of sales and purchases for each item in the store.
The classic solution can be like
SELECT ProductID,
Quantity,
(SELECT Count(*)
FROM AdventureWorks.Purchasing.PurchaseOrderDetail
WHERE PurchaseOrderDetail.ProductID = p.ProductID) TotalPurchases,
(SELECT Count(*)
FROM AdventureWorks.Sales.SalesOrderDetail
WHERE SalesOrderDetail.ProductID = p.ProductID) TotalSales
FROM (SELECT DISTINCT ProductID,
Quantity
FROM AdventureWorks.Production.ProductInventory) p
Trying to convert to window functions gives me wrong results:
SELECT DISTINCT d.ProductID,
Quantity,
Count(d.ProductID)
OVER(
PARTITION BY d.ProductID) TotalPurchases,
Count(d2.ProductID)
OVER(
PARTITION BY d2.ProductID) TotalSales
FROM (SELECT DISTINCT ProductID,
Quantity
FROM AdventureWorks.Production.ProductInventory) p
INNER JOIN AdventureWorks.Purchasing.PurchaseOrderDetail d
ON p.ProductID = d.ProductID
INNER JOIN AdventureWorks.Sales.SalesOrderDetail d2
ON p.ProductID = d2.ProductID
ORDER BY d.ProductID
Why this is wrong? How can I correct it?
You should change INNER JOIN to LEFT JOIN
Because when you inner join, result will miss productid which from ProductInventory table does not have PurchaseOrderDetail or SalesOrderDetail.