SQL QUERY case with a condition - sql

I have a sql query where I have to get records count, I am getting counts correctly with the current query but I want to only get counts for records where 'Unchecked Count' is not zero.
SELECT
dbo.Customer.AccountNo AS Cust_Acc_No,
dbo.Customer.Name AS [Customer Name],
dbo.Customer.Adrs1 AS Cust_Address_1,
dbo.Customer.Adrs2 AS Cust_Address_2,
dbo.Customer.City AS Cust_City,
dbo.Customer.Province,
dbo.Customer.PostalCode AS Cust_Postal_Code,
dbo.Customer.Email1 AS Email,
CAST(dbo.Customer.AccStatus AS int) AS [Account Status],
dbo.Customer.ID AS CID,
case when COUNT(dbo.Manifest.ID) <
sum( CASE WHEN (dbo.Manifest.CheckedBy IS NULL OR
(LTRIM(RTRIM(dbo.Manifest.CheckedBy)) = '')) THEN 1 ELSE 0 END)
then COUNT(dbo.Manifest.ID) else
sum( CASE WHEN (dbo.Manifest.CheckedBy IS NULL OR
(LTRIM(RTRIM(dbo.Manifest.CheckedBy)) = '')) THEN 1 ELSE 0 END)
end as [Unchecked Count],
case when COUNT(dbo.Manifest.ID) <
sum( CASE WHEN (dbo.Manifest.CheckedBy IS not NULL OR
(LTRIM(RTRIM(dbo.Manifest.CheckedBy))! = '')) THEN 1 ELSE 0 END)
then COUNT(dbo.Manifest.ID) else
sum( CASE WHEN (dbo.Manifest.CheckedBy IS not NULL OR
(LTRIM(RTRIM(dbo.Manifest.CheckedBy))! = '')) THEN 1 ELSE 0 END)
end as [Checked_Count],
COUNT(dbo.Manifest.ID) as Total
FROM
dbo.Customer inner JOIN dbo.Manifest ON dbo.Customer.AccountNo = dbo.Manifest.FKAccountNo
GROUP BY
dbo.Customer.AccountNo,
dbo.Customer.Name,
dbo.Customer.Adrs1,
dbo.Customer.City,
dbo.Customer.Province,
dbo.Customer.Adrs2,
dbo.Customer.Email1,
dbo.Customer.PostalCode,
dbo.Customer.AccStatus,
dbo.Customer.ID,Manifest.FKAccountNo

Try Having clause after your group by clause
having [Unchecked Count] > 0
Full query
SELECT dbo.Customer.AccountNo AS Cust_Acc_No, dbo.Customer.Name AS [Customer Name], dbo.Customer.Adrs1 AS Cust_Address_1, dbo.Customer.Adrs2 AS Cust_Address_2, dbo.Customer.City AS Cust_City,
dbo.Customer.Province, dbo.Customer.PostalCode AS Cust_Postal_Code, dbo.Customer.Email1 AS Email, CAST(dbo.Customer.AccStatus AS int) AS [Account Status], dbo.Customer.ID AS CID,
case when COUNT(dbo.Manifest.ID) < sum( CASE WHEN (dbo.Manifest.CheckedBy IS NULL OR
(LTRIM(RTRIM(dbo.Manifest.CheckedBy)) = '')) THEN 1 ELSE 0 END)
then COUNT(dbo.Manifest.ID) else
sum( CASE WHEN (dbo.Manifest.CheckedBy IS NULL OR
(LTRIM(RTRIM(dbo.Manifest.CheckedBy)) = '')) THEN 1 ELSE 0 END)
end
as [Unchecked Count],
case when COUNT(dbo.Manifest.ID) < sum( CASE WHEN (dbo.Manifest.CheckedBy IS not NULL OR
(LTRIM(RTRIM(dbo.Manifest.CheckedBy))! = '')) THEN 1 ELSE 0 END)
then COUNT(dbo.Manifest.ID) else
sum( CASE WHEN (dbo.Manifest.CheckedBy IS not NULL OR
(LTRIM(RTRIM(dbo.Manifest.CheckedBy))! = '')) THEN 1 ELSE 0 END)
end
as [Checked_Count],
COUNT(dbo.Manifest.ID) as Total
FROM dbo.Customer inner JOIN
dbo.Manifest ON dbo.Customer.AccountNo = dbo.Manifest.FKAccountNo
GROUP BY dbo.Customer.AccountNo, dbo.Customer.Name, dbo.Customer.Adrs1, dbo.Customer.City, dbo.Customer.Province, dbo.Customer.Adrs2, dbo.Customer.Email1, dbo.Customer.PostalCode, dbo.Customer.AccStatus,
dbo.Customer.ID,Manifest.FKAccountNo
having [Unchecked Count] > 0

You can query the result of the other query.
SELECT * FROM ( <your query> ) AS T WHERE [Unchecked Count] > 0

Thank you AlexanderW and Shakti for your answers.I tried both of your suggestions but 'Unchecked Count' is a alias, that is why I was getting 'invalid Column error'. But your answers helped me to solve the problem. Here is how it is working now, please let me know if you have better suggestion/s..
WITH OnlyUnchecked AS(<MyQuery>)
SELECT *
FROM OnlyUnchecked
WHERE [Unchecked Count]>0

Related

How to split data in SQL

I have the following code:
select
FeeEarnerID,
(
select
(select [name] from [User] AS u where u.userid=f.userid)
from
feeearner AS f
where
f.FeeEarnerID=aa.FeeEarnerID
) FeeEarner,
sum(aa.FEES) Fees,
sum(aa.DISB) Disbursements,
sum(aa.CREDITORS) Creditors
from
(
SELECT
FeeEarner.FeeEarnerID,
case when WIPTransaction.WIPTransactionTypeID IN (1,17,18,20,21,25) then WIPTransaction.Amount else 0 end 'FEES',
case when WIPTransaction.WIPTransactionTypeID IN (2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,26,27,28,29) then WIPTransaction.Amount else 0 end 'DISB',
case when WIPTransaction.WIPTransactionTypeID IN (24) then WIPTransaction.Amount else 0 end 'CREDITORS'
FROM
(
(
FeeEarner
JOIN
WIPTransaction ON FeeEarner.FeeEarnerID = WIPTransaction.FeeEarnerID
)
JOIN
WIPTransactionType ON WIPTransactionType.WIPTransactionTypeID = WIPTransaction.WIPTransactionTypeID
)
WHERE
(WIPTransaction.TransactionDate BETWEEN '2020-10-01' AND '2020-12-31')
)
AS aa
group by
FeeEarnerID
Used Table names: WIPtransaction, WIPtransactiontype, Feeearner
I want to display two more columns at the end of the output, namely: Invoiced and Uninvoiced.
The "Invoicenumber" field in the "WIPtransaction" database will be tested for this. If the "Invoicenumber" is NULL - the transaction amount will be added to a sum in the uninvoiced column and if "Invoicenumber" contains a number - the transaction amount will be added to a sum in the invoiced column.
What is the code that I would need to write and where would it be placed?
select
FeeEarnerID,
(
select
(select [name] from [User] AS u where u.userid=f.userid)
from
feeearner AS f
where
f.FeeEarnerID=aa.FeeEarnerID
) FeeEarner,
sum(aa.FEES) Fees,
sum(aa.DISB) Disbursements,
sum(aa.CREDITORS) Creditors,
----------
SUM( InvoicedAmount) AS InvoicedAmount,
SUM(UnInvoicedAmount) AS UnInvoicedAmount
----------
from
(
SELECT
FeeEarner.FeeEarnerID,
case when WIPTransaction.WIPTransactionTypeID IN (1,17,18,20,21,25) then WIPTransaction.Amount else 0 end 'FEES',
case when WIPTransaction.WIPTransactionTypeID IN (2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,26,27,28,29) then WIPTransaction.Amount else 0 end 'DISB',
case when WIPTransaction.WIPTransactionTypeID IN (24) then WIPTransaction.Amount else 0 end 'CREDITORS',
----------
CASE WHEN WIPTransaction.Invoicenumber IS NOT NULL THEN WIPTransaction.Amount END AS InvoicedAmount,
CASE WHEN WIPTransaction.Invoicenumber IS NULL THEN WIPTransaction.Amount END AS UnInvoicedAmount
----------
FROM
FeeEarner
JOIN
WIPTransaction ON FeeEarner.FeeEarnerID = WIPTransaction.FeeEarnerID
JOIN
WIPTransactionType ON WIPTransactionType.WIPTransactionTypeID = WIPTransaction.WIPTransactionTypeID
WHERE
WIPTransaction.TransactionDate BETWEEN '2020-10-01' AND '2020-12-31'
)
AS aa
group by
FeeEarnerID
You can remove your derived query and combine it all into one. The FeeEarner double sub-query can also be optimized:
select
FeeEarnerID,
(
select [name] from [User] AS u where u.userid=FeeEarner.userid
) FeeEarner,
sum(case when WIPTransaction.WIPTransactionTypeID IN (1,17,18,20,21,25) then WIPTransaction.Amount else 0 end) Fees,
sum(case when WIPTransaction.WIPTransactionTypeID IN (2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,26,27,28,29) then WIPTransaction.Amount else 0 end) Disbursements,
sum(case when WIPTransaction.WIPTransactionTypeID IN (24) then WIPTransaction.Amount else 0 end) Creditors,
SUM(CASE WHEN WIPTransaction.Invoicenumber IS NOT NULL THEN WIPTransaction.Amount END) AS InvoicedAmount,
SUM(CASE WHEN WIPTransaction.Invoicenumber IS NULL THEN WIPTransaction.Amount END) AS UnInvoicedAmount
FROM
FeeEarner
JOIN
WIPTransaction ON FeeEarner.FeeEarnerID = WIPTransaction.FeeEarnerID
JOIN
WIPTransactionType ON WIPTransactionType.WIPTransactionTypeID = WIPTransaction.WIPTransactionTypeID
WHERE
WIPTransaction.TransactionDate BETWEEN '2020-10-01' AND '2020-12-31'
group by
FeeEarnerID;

Subquery to pull sum amount from different table and group by salesperson

--I am trying to simply add one subquery to take the total sales of each salesperson in relation to their quotes. I am at a loss and hopefully someone can help.
select sp.FIRST_NAME + ' ' + sp.LAST_NAME,
sum(case when sq.SAL_QUOTE_STATUS_ID = '1' then 1 else 0 end) as [Created],
sum(case when sq.SAL_QUOTE_STATUS_ID = '4' then 1 else 0 end) as [Ordered],
sum(case when sq.SAL_QUOTE_STATUS_ID = '3' then 1 else 0 end) as [Rejected],
sum(sq.AMOUNT_INCLUDING_TAX) as [Amount],
sum(sq.COST) as [Cost],
sum(sq.AMOUNT_INCLUDING_TAX - sq.COST) as [Profit],
round(100 * (case when sum(sq.AMOUNT_INCLUDING_TAX) > 0 then
(sum(sq.AMOUNT_INCLUDING_TAX) -
sum(sq.COST)) / sum(sq.AMOUNT_INCLUDING_TAX) else 0 end), 3) as [GP%],
(Select sum(so.amount_including_tax)
from SAL_SALES_ORDER so
where so.SALESPERSON_ID = sp.SALESPERSON_ID) as [YTD Sales]
from SAL_SALES_QUOTE sq
inner join CRM_SALESPERSON sp on sp.SALESPERSON_ID = sq.SALESPERSON_ID
where sq.CREATED_DATE > '01-01-2018'
group by sp.FIRST_NAME + ' ' + sp.LAST_NAME
I took your subquery out of the select, made it into a result set to join on , and then pulled the sum from there.
select sp.FIRST_NAME + ' ' + sp.LAST_NAME,
sum(case when sq.SAL_QUOTE_STATUS_ID = '1' then 1 else 0 end) as [Created],
sum(case when sq.SAL_QUOTE_STATUS_ID = '4' then 1 else 0 end) as [Ordered],
sum(case when sq.SAL_QUOTE_STATUS_ID = '3' then 1 else 0 end) as [Rejected],
sum(sq.AMOUNT_INCLUDING_TAX) as [Amount],
sum(sq.COST) as [Cost],
sum(sq.AMOUNT_INCLUDING_TAX - sq.COST) as [Profit],
round(100 * (case when sum(sq.AMOUNT_INCLUDING_TAX) > 0 then
(sum(sq.AMOUNT_INCLUDING_TAX) -
sum(sq.COST)) / sum(sq.AMOUNT_INCLUDING_TAX) else 0 end), 3) as [GP%],
sum([x.ytd_sales]) AS YTD_Sales
from SAL_SALES_QUOTE sq
inner join CRM_SALESPERSON sp on sp.SALESPERSON_ID = sq.SALESPERSON_ID
inner join (Select so.salesperson_id, sum(so.amount_including_tax) AS [YTD Sales]
from SAL_SALES_ORDER so
group by so.salesperson_id) x
ON x.salesperson_id = sp.salesperson_id
where sq.CREATED_DATE > '01-01-2018'
group by sp.FIRST_NAME + ' ' + sp.LAST_NAME

Update a complex SQL query to add a new column with the sum of two columns

The below SQL query creates a table with n number of columns named in the next line.
...., curr_amount, tax_amount, ....
I am having a very tough time updating the below query to create a new column called total and position it exactly after tax_amount column and the total column should contain the values that are obtained after sum of curr_amount & tax_amount.
I have been working on this from more than one day but couldn't figure it out.
P.S. Still a noob here. Thanks alot for your time.
.
SELECT Isnull(t.total_month, 'Total') total_month,
t.tax_amount,
t.curr_amount,
t.usage_qty,
t.kh_qty,
t.bill_cnt
FROM (SELECT dbo.Sigmadf(bm.posted_date, 'YYYY-MM') total_month,
Sum(CASE
WHEN rr.usage_qty IS NULL THEN 0
ELSE Cast (rr.usage_qty AS NUMERIC(18, 2))
END) usage_qty,
Sum(CASE
WHEN bm.curr_amount IS NULL THEN 0
ELSE bm.curr_amount
END) curr_amount,
Sum(CASE
WHEN bm.adj_amount IS NULL THEN 0
ELSE bm.adj_amount
END) adj_amount,
Sum(CASE
WHEN bm.bal_fwd_amount IS NULL THEN 0
ELSE bm.bal_fwd_amount
END) bal_forward,
Sum(CASE
WHEN bm.tax_amount IS NULL THEN 0
ELSE bm.tax_amount
END) tax_amount,
Sum(CASE
WHEN bm.due_amount IS NULL THEN 0
ELSE bm.due_amount
END) due_amount,
Sum(CASE
WHEN bm.last_total_paid_amount IS NULL THEN 0
ELSE bm.last_total_paid_amount * -1
END) paid_amount,
Sum(CASE
WHEN bm.bill_print = 'Y' THEN 1
ELSE 0
END) pdf_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '0' THEN 1
ELSE 0
END) reg_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '1' THEN 1
ELSE 0
END) ftime_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '9999' THEN 1
ELSE 0
END) ltime_cnt,
Count(*) bill_cnt,
Sum(CASE
WHEN bill_status = '01' THEN 1
ELSE 0
END) canc_cnt,
Sum(CASE
WHEN bill_status = '01' THEN
CASE
WHEN rr.usage_qty IS NULL THEN 0
ELSE Cast (rr.usage_qty AS NUMERIC(18, 2))
END
ELSE 0
END) canc_usg,
Sum(CASE
WHEN vis.kh_qty IS NULL THEN 0
ELSE Cast(vis.kh_qty AS NUMERIC(18, 2))
END) kh_qty
FROM bill_master bm WITH (nolock)
INNER JOIN (SELECT bill_no,
Sum(CASE
WHEN vpb.recurr_charge_type IN ( 'T4',
'SLF' )
THEN
CASE
WHEN vpb.print_qty = 'Y'
AND vpb.usage_qty IS NOT NULL
THEN
Cast (vpb.usage_qty AS
NUMERIC(18, 2))
ELSE 0
END
ELSE 0
END) usage_qty
FROM v_print_bills_all vpb
GROUP BY bill_no) rr
ON rr.bill_no = bm.bill_no
LEFT OUTER JOIN vis_bill_master_cr vis WITH (nolock)
ON bm.bill_no = vis.bill_no
WHERE 1 = 1
AND dbo.Trunc(bm.posted_date) >= '20150101'
AND dbo.Trunc(bm.posted_date) <= '20151124'
AND bm.posted_date IS NOT NULL
AND bm.cust_id NOT IN (SELECT cc.code_type cust_id
FROM code_table cc WITH (nolock)
WHERE cc.code_tabname = 'RptExclCust'
AND cc.code_value = 'cust_id')
GROUP BY dbo.Sigmadf(bm.posted_date, 'YYYY-MM') WITH rollup)t
I must say that the explanation is not so clear.
From my understanding, you want the total of two columns.
So, wrap all your query between parenthesis, call it subQuery, and make the sum of the two columns on top:
SELECT subQuery.total_month as bill_date,
subQuery.curr_amount as amount,
subQuery.tax_amount tax,
subQuery.curr_amount + subQuery.tax_amount as [total],
...
FROM
(..your entire query here..) as subQuery

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

How do you get the product of two case statements

I am trying to combine case statements using the following code and keep encountering errors.
SELECT
dbo.COL_TBL_WAGES.[Job Group],
SUM(CASE
WHEN COL_V_COST.EMP_TNG_RL_CD = 'ST'
THEN ([CountOfEMP_TNG_STT_DT] *
(WHEN IsNumeric([TBL_VCOURSE.Length])
THEN TBL_VCOURSE ELSE 0 END) AS ST_Hours
It looks like you want this since you have two CASE expressions in your original:
SELECT dbo.COL_TBL_WAGES.[Job Group],
SUM(CASE
WHEN COL_V_COST.EMP_TNG_RL_CD = 'ST'
THEN [CountOfEMP_TNG_STT_DT]
ELSE 0 END
* CASE
WHEN IsNumeric([TBL_VCOURSE.Length]) = 1
THEN TBL_VCOURSE
ELSE 0 END
) AS ST_Hours
Edit, based on your comment your query will be similar to this:
SELECT dbo.COL_TBL_WAGES.[Job Group],
SUM(CASE
WHEN COL_V_COST.EMP_TNG_RL_CD = 'ST'
THEN [CountOfEMP_TNG_STT_DT] ELSE 0 END
* CASE
WHEN IsNumeric([COL_TBL_VCOURSE].[Length]) = 1
THEN COL_TBL_VCOURSE.[LENGTH]
ELSE 0 END) AS ST_Hours,
SUM(CASE
WHEN COL_V_COST.EMP_TNG_RL_CD = 'ST'
THEN [CountOfEMP_TNG_STT_DT]*CAST([2011 Total] AS FLOAT) ELSE 0 END
* CASE
WHEN IsNumeric([COL_TBL_VCOURSE].[LENGTH]) = 1
THEN CAST([COL_TBL_VCOURSE].[LENGTH] AS FLOAT) ELSE 0 END) AS ST_Cost