SUM field not summing - sql

Similar to my last question. Heres my code:
SELECT TR.ITEMNO,
SUM ( TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'PO' THEN 1 ELSE 0 END ) AS SUM_IN,
SUM ( TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'MH' THEN 1 ELSE 0 END ) AS SUM_OUT
FROM IQMS.TRANSLOG TR
WHERE TR.ITEMNO = '200672'
GROUP BY TR.ITEMNO
HAVING SUM ( TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'PO' THEN 1 ELSE -1 END ) < 0
ORDER BY TR.ITEMNO
The code is running fine but it is not summing anything for SUM_OUT. I know for a fact however that there are numbers there to be summed. Is there something obvious that I am missing? Thanks in advance!! :)

Try...
SUM (TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'PO' THEN 1 ELSE 0 END )
OVER(PARTITION BY TR.ITEMNO) AS SUM_IN,
SUM ( TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'MH' THEN 1 ELSE 0 END )
OVER(PARTITION BY TR.ITEMNO) AS SUM_OUT,

Related

Using a case column within another case in select clause

I have a select clause with a case statement and I need to create another case statement comparing the column created by the previous case statement. Something like this:
select client
,discount
,(case when sales_avg>10000 then 30
when sales_avg>5000 then 20
else 0 end) discount_rule
,(case when discount < discount_rule then 1 else 0 end) status
from sales;
I get a message that discount_rule is unknown. How can I accomplish that?
You can use a Common Table Expression (CTE) and reference a CTE within a CTE as:
with CTE_discount_rule as
(
select client,
discount,
(case when sales_avg>10000 then 30
when sales_avg>5000 then 20
else 0 end) as discount_rule
from sales
),
CTE_Final_Status as
(
select client,
discount,
discount_rule,
(case when discount < discount_rule then 1 else 0 end) as status
from CTE_discount_rule
)
select * from CTE_Final_Status;
The simplest way is to use a subquery that returns the column discount_rule:
select t.client, t.discount, t.discount_rule,
case
when discount < discount_rule then 1
else 0
end status
from (
select client, discount,
case
when sales_avg > 10000 then 30
when sales_avg > 5000 then 20
else 0
end discount_rule
from sales
) t

How to aggregate and make a ratio between two fields from a CTE

I have a query which return a flag wheter a client who made a contract with my company this year is new or returning:
WITH Resultset AS(
SELECT
Cnt = COUNT(*)
,KliRC --personal identification number
FROM dbo.Smlouvy
WHERE VyplacenaCastka > 0
GROUP BY KliRC
)
SELECT
s.KliRC
,CASE WHEN Cnt > 1 THEN 1 ELSE 0 END AS Novy --new client
,CASE WHEN Cnt = 1 THEN 1 ELSE 0 END AS Stavajici --existing client
FROM Resultset JOIN dbo.Smlouvy s ON s.KliRC = resultset.KliRC
WHERE (YEAR(DatumZadosti) = YEAR(GETDATE())) AND (s.KliRC NOT LIKE '%x')
Now, I need to aggregate all the new and existing clients and make a ratio between them.
Any ideas? Thanks in advance.
I think this does what you want:
WITH Resultset AS (
SELECT COUNT(*) as cnt,
KliRC --personal identification number,
(CASE WHEN COUNT(*) > 1 THEN 1 ELSE 0 END) AS Novy --new client
(CASE WHEN COUNT(*) = 1 THEN 1 ELSE 0 END) AS Stavajici
FROM dbo.Smlouvy
WHERE VyplacenaCastka > 0
GROUP BY KliRC
)
SELECT SUM(Novy) / SUM(Stavajici)
FROM Resultset r JOIN
dbo.Smlouvy s
ON s.KliRC = r.KliRC
WHERE YEAR(DatumZadosti) = YEAR(GETDATE()) AND
s.KliRC NOT LIKE '%x';
Your query can be simplified to
SELECT SUM(Novy)*1.0/SUM(Stavajici)
FROM (
SELECT KliRC
,CASE WHEN COUNT(*) OVER(PARTITION BY KliRC) > 1 THEN 1 ELSE 0 END AS Novy --new client
,CASE WHEN COUNT(*) OVER(PARTITION BY KliRC) = 1 THEN 1 ELSE 0 END AS Stavajici --existing client
FROM dbo.Smlouvy
WHERE YEAR(DatumZadosti) = YEAR(GETDATE()) AND KliRC NOT LIKE '%x'
) T

Is it possible to use 'case' with and in 'count'?

Is it possible to use case with and in count
SELECT branches.NAME AS agence,
count(
CASE loanstatus
WHEN '1'
AND Datepart(month,loanaccount.issuedate)= 2 THEN 1
ELSE NULL
END )AS nombre_de_credits_demande ,
count(
CASE loanstatus
WHEN '2' datepart(month,loanaccount.chargeoffdate)= 2 THEN 1
ELSE NULL
END )AS nombre_de_credits_approuve
please help me
You can use it with count(). I prefer sum():
select Branches.Name as Agence,
sum(case when LoanStatus = '1' and
datepart(MONTH, LoanAccount.IssueDate) = 2
then 1 else 0
end ) as Nombre_de_Crédits_Demandé ,
sum(case when LoanStatus = '2' and
datepart(MONTH, LoanAccount.IssueDate) = 2
then 1 else 0
end ) as Nombre_de_Crédits_Approuvé
The issue with your code was not the count() versus sum() it is the mixing of two different case syntaxes. When you use case <var> when <val>, you cannot include any other conditions. Just use when with the full conditions that you want.
And, if you like, you can use count() instead of sum().
And, for conciseness, I prefer the month() function:
select Branches.Name as Agence,
sum(case when LoanStatus = '1' and MONTH(LoanAccount.IssueDate) = 2
then 1 else 0
end ) as Nombre_de_Crédits_Demandé ,
sum(case when LoanStatus = '2' and MONTH(LoanAccount.IssueDate) = 2
then 1 else 0
end ) as Nombre_de_Crédits_Approuvé
you can achieve your goal through this query.
select
branches.name as agence
,(select COUNT(1) from <table_name> where loginstatus=1 and Datepart(month,loanaccount.issuedate)= 2) as nombre_de_credits_demande
,(select COUNT(1) from <table_name> where loginstatus=2 and Datepart(month,loanaccount.issuedate)= 2) as AS nombre_de_credits_approuve
from <Table_name>

Counting specific cells in SQL Server

I have a table like this:
The RP Type column specifies the type of rate plan which can be (low, high, normal)
I want to create a view in which I can see number of each subscribers' which can be high, normal, low.
It should be like this I guess:
Create view t as
select
SubID,
Count(something) as NumeOfHIGH,
Count(Something) as NumOfLOW,
Count(Something) as NumOfNormal
Group by SubID
I might be wrong..Thank you
You can form your query in the following way:
SELECT SubID,
SUM (
CASE
WHEN RP_Type='High' THEN 1
ELSE 0 END
) AS NumOfHigh,
SUM (
CASE
WHEN RP_Type='Low' THEN 1
ELSE 0 END
) AS NumOfLow,
SUM (
CASE
WHEN RP_Type='Normal' THEN 1
ELSE 0 END
) AS NumOfNormal
FROM
<table_name>
Group by SubID
If there are multiple RP_Type in each of High, Low and Normal Category, you can include each type with WHEN in respective category.
For more information and reference: Conditional Processing using CASE
i tried this :
select SubscriberID
,COUNT(*) AS NumOfPlans
,SUM([SP active days]) as ActiveDays
,SUM(Case when [RP Type]='low' then 1 else 0 end ) as #LowPlan
,SUM(Case when [RP Type]='high' then 1 else 0 end ) as #NormalPlan
,SUM(Case when [RP Type]='high' then 1 else 0 end ) as #HighPlan
,SUM(Case when [RP Type]='promotion' then 1 else 0 end ) as #PromotionsPlan
,SUM(Case when [RP Type]='portal' then 1 else 0 end ) as #PortablePlan
,SUM(Case when [RP Type]='newyear' then 1 else 0 end ) as #NewYearPlan
,SUM(Case when [RP Type]='hamaval1' then 1 else 0 end ) as #HamrahAval1Plan
,SUM(Case when [RP Type]='hamaval2' then 1 else 0 end ) as #HamrahAval2Plan
,SUM(Case when [RP Type]='samsung' then 1 else 0 end ) as #SamsungPlan
,SUM(Case when [RP Type]='DEMO' then 1 else 0 end ) as #DemoPlan
,SUM(Case when [RP Type]IS null then 1 else 0 end ) as #NuLL
,SUM([Extra Quota]) as SumGIG
from [Cus Consumption].[dbo].CustData
where [Expiry Date]<= '2014 - 01 - 15'
group by [SubscriberID]
The ironic thing is that i does not return a correct answer..I don't know why #Rohit Aggrawal
is this helpful?
Create view t as
select From [tableName]
[Rp Type],count(*) as NumberOfSubscribers
Group by [Rp Type]
This gives you Number of subscribers in each type, and type
Hope this helpful

Using case statement on sum aggregate

I'm trying to run a case on an aggregate sum but can't seem to get this working...essentially I want to return 1 if the sum of the column is > 0...
SELECT Shop.Brands, Shop.Brand, Shop.T3, Shop.ShopName, Shop.Period
CASE WHEN sum(PLData.Actuals) > 0 THEN 1 ELSE 0 END as Actuals,
CASE when sum(PLData.Budgets) > 0 THEN 1 ELSE 0 END as Budget,
CASE when sum(pldata.ForecastLedger) > 0 THEN 1 ELSE 0 END as Forecast
FROM SunFinance.dbo.Shop Shop LEFT OUTER JOIN SunFinance.dbo.PLData PLData ON Shop.T3 = PLData.Shop
WHERE Shop.BusinessType In ('CORPORATE','RETAIL','WHOLESALE')
AND PLData.Account Like '488%')
GROUP by shop.brand, shop.brands, shop.t3, shop.shopname, Shop.Period
Where am I going wrong?
If your DBMS doesn't let you use aggregates in case expressions, you can try to do the aggregation first in an inline view, then do your CASE expressions.
WITH RESULTS AS (
SELECT Shop.Brands
, Shop.Brand
, Shop.T3
, Shop.ShopName
, Shop.Period
, sum(PLData.Actuals) as Actuals
, sum(PLData.Budgets) as Budget,
, sum(pldata.ForecastLedger) as Forecast
FROM SunFinance.dbo.Shop Shop
LEFT OUTER JOIN SunFinance.dbo.PLData PLData
ON Shop.T3 = PLData.Shop
WHERE Shop.BusinessType In ('CORPORATE','RETAIL','WHOLESALE')
AND PLData.Account Like '488%'
GROUP by shop.brand, shop.brands, shop.t3, shop.shopname, Shop.Period
)
SELECT brands, brand, t3, shopname, period,
case when actuals > 0 then 1 else 0 end as actuals,
case when budget > 0 then 1 else 0 end as budget,
case when forecast > 0 then 1 else 0 end as forecast
FROM results