SQL COUNT specific unit IF another field <> 0 - sql

I have a query that has a select statement that contains the following:
,COUNT(u.[Unit])
,up.[Number_Of_Stops]
I need to only count the units where number of stops <> 0. This has more details in the query so I can't just say WHERE number_of_stops <> 0. It has to be within the select statement.
Thanks

Try:
SUM(CASE WHEN up.[Number_Of_Stops] != 0 THEN 1 ELSE 0 END) AS countWhereNumStopsNotZero
(Edit: original answer said "COUNT" not "SUM")

Related

Using Max(boolean) in a case statement

I am made a temp table of accounts in a database with booleans that provide insight about the accounts. Some customers have multiple accounts so I am grouping them together and was trying to look at the MAX(Boolean) to set a status field.
My query kinda looks like:
with t as (Select lngCustomerNumber,
Case
When 'Criteria for being Active' Then 1
End as blnActive,
Case
When 'Criteria for unexpired' Then 1
End as blnUnexpired
From AccountTable)
Select t.CustomerNumber,
Case
When Max(t.blnActive) = 1
AND Max(t.blnUnexpired) = 1 Then 'Active/Unexpired'
When Max(t.blnActive) = 1
AND Max(t.blnUnexpired) = 0 Then 'Active/Expired'
When Max(t.blnActive) = 0
AND Max(t.blnUnexpired) = 1 Then 'Inactive/Unexpired'
When Max(t.blnActive) = 0
AND Max(t.blnUnexpired) = 0 Then 'Inactive/Expired'
End As strLicenseStatus
From T
Group By t.CustomerNumber
Anything where it checks if the Max(Boolean) = 1 will calc to True correctly, but if I do Max(Boolean) = 0 or Max(Boolean) <> 1 then it does not calc to True when it should.
I have tested by just looking at the grouped Temp Table with each boolean bringing back its Max() value and the ones that should be 0 are coming back as 0.
As a workaround, I have tried
Where t.CustomerNumber NOT IN (SELECT t2.CustomerNumber
FROM t t2
WHERE t2.blnUnexpired = 1
AND t2.CustomerNumber = t.CustomerNumber )
And that does give me the results that I am looking for but I have millions of rows coming back so it has been timing out after many hours, where the previous method was able to run in less than an hour.
I have some other data in my query, the one presented is a much smaller version used to highlight my issue.
Any recommendations on how I can make this work?
Thank you.
When you are defining your blnActive and blnUnexpired cases, you only have the "1" case defined, which means if it doesn't meet these criteria, it will be null. Try adding else 0 to each case:
with t as (Select lngCustomerNumber,
Case
When 'Criteria for being Active' Then 1
Else 0
End as blnActive,
Case
When 'Criteria for unexpired' Then 1
Else 0
End as blnUnexpired
From AccountTable)

How can I avoid zero values in an aggregate?

I have a query which is pulling back data correctly, but about a quarter of the lines of data are unnecessary because they have 0 in the primary data field. Here is the line I wrote to create that primary data field. How can I exclude any case where the output value for amort_FY2020 is 0?
sum(case when f.sales_revenue_period_calendar_sid in ('20200101',
'20200201',
'20200301',
'20200401',
'20200501',
'20200601',
'20200701',
'20200801',
'20200901',
'20201001',
'20201101',
'20201201')
then f.sales_revenue_before_tax_usd_amount
else 0 end) as amort_FY2020
Depending on your database, you can use:
having amort_FY2020 <> 0
Or may may need to repeat the expression:
sum(case when f.sales_revenue_period_calendar_sid in ('20200101','20200201','20200301','20200401','20200501','20200601','20200701','20200801','20200901','20201001','20201101','20201201')
then f.sales_revenue_before_tax_usd_amount else 0
end) <> 0

Case When formula to COUNT on results tab

On results tab of saved search, I would like to display a COUNT of Opportunities that do not have SLX in Title, Memo or Item Name. I'm using a transaction saved search.
I have tried a formula(numeric)results column and it returns incorrect results of one per grouped rep:
Formula(Numeric) Summary type: COUNT
CASE WHEN({title} = 'SLX') Or ({memo} = 'SLX') Or ({item.name} = 'SLX') THEN 1 ELSE 0 END
Counts one per Rep (grouped).
Hmmm . . . I think sum() is more appropriate:
SUM(CASE WHEN({title} = 'SLX') Or ({memo} = 'SLX') Or ({item.name} = 'SLX') THEN 1 ELSE 0 END)
Your expression is equivalent to COUNT(*), because COUNT() counts non-NULL values and all the values are either 1 or 0.

Oracle SQL, IF statements

I’m running a query from a table that has info on account numbers, settled charges , the write off figure, and the reason for the write off; so the table is called group_write_off and the table headings, account_id, charge_settled_date, total_charge_amount, amount_written_off, write_off_reason. What I want to do, is pull everything through, so
Select * from
group_write_off
but for any case where the write_off_reason includes the word ‘Audit’, I want amount_written_off to show as 0 (zero), for all others i want the original amount_written_off to show.
Many thanks.
Use CASE expression.
SELECT CASE WHEN write_off_reason='Audit' THEN 0 ELSE amount_written_off END
FROM group_write_off
Also try below for checking if Audit word is present in column write_off_reason by using INSTR() function
SELECT CASE WHEN INSTR(write_off_reason,'Audit') = 0 THEN 0 ELSE amount_written_off END
FROM group_write_off
If you want more words
SELECT CASE WHEN INSTR(write_off_reason,'Audit') = 0 THEN 0
WHEN INSTR(write_off_reason,'admin') = 0 THEN 0
ELSE amount_written_off END
FROM group_write_off

Multiple columns within a single CASE statement

I'm sure this has be covered many times so please pardon my repeat. I have a query that works but currently has 6 CASE statements within one select. Someone mentioned that it would be best optimized by putting all my WHEN conditions within a single CASE. However, I'm unable to achieve this
select right(RTRIM(region),5) as cell_id,
sum(CASE WHEN LEFT(cparty,3) in ('999','998','997') THEN chargeduration/60 else 0 END) AS OnNet_Minutes,
sum(CASE WHEN LEFT(cparty,3) in ('996','995') THEN chargeduration/60 else 0 END) AS OffNet_C_Minutes,
sum(CASE WHEN LEFT(cparty,3) in ('994','993','992') THEN chargeduration/60 else 0 END) AS OffNet_A_Minutes,
sum(CASE WHEN LEFT(cparty,3) in ('991','990') THEN chargeduration/60 else 0 END) AS OffNet_S_Minutes,
sum(CASE WHEN LEFT(cparty,2) = '00' THEN chargeduration/60 else 0 END) AS OffNet_T_Minutes,
sum(CASE WHEN len(cparty) < 6 and LEFT(cparty,1) <> 0 THEN chargeduration/60 else 0 END) AS SC_Minutes
from August.dbo.cdr20130818
where CHARGEDURATION > 0 and ISNULL(region,'''')<>'''' and LEN(region) > 5
group by right(RTRIM(region),5)
order by right(RTRIM(region),5) asc
In your case, you can't put them all into one CASE, since the results all go into different columns of the select.
BTW, you should remove your ISNULL(region, '''') <> '''' condition, as it's redundant when paired with the LEN(region) > 5 condition. (When region is null, then LEN(region) is also null, and NULL > 5 is false.)
I think you have it right, six different SUM()'s that each have meaning on their own.
If all of your criteria were in the same CASE statement you'd lose detail, you'd be returning the SUM() of your currently separate statements combined into one.
Combining redundant criteria in the WHERE clause can clean up a CASE statement, but you don't have anything completely redundant here.