Using a case column within another case in select clause - sql

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

Related

How to exclude 0 from count()? in sql?

I have a code as below where I want to count number of first purchases for a given period of time. I have a column in my sales table where if the buyer is not a first time buyer, then is_first_purchase = 0
For example:
buyer_id = 456391 is already an existing buyer who made purchases on 2 different dates.
Hence is_first_purchase column will show as 0 as per below.
If i do a count() on is_first_purchase for this buyer_id = 456391 then it should return 0 instead of 2.
My query is as follows:
with first_purchases as
(select *,
case when is_first_purchase = 1 then 'Yes' else 'No' end as first_purchase
from sales)
select
count(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
It returned the below which is not an intended output
Appreciate if someone can help explain how to exclude is_first_purchase = 0 from the count, thanks.
Because COUNT function count when the value isn't NULL (include 0), if you don't want to count, need to let CASE WHEN return NULL
There are two ways you can count as your expectation, one is SUM other is COUNT but remove the part of else 0
SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
COUNT(case when first_purchase = 'Yes' then 1 end) as no_of_first_purchases
From your question, I would combine CTE and main query as below
select
COUNT(case when is_first_purchase = 1 then 1 end) as no_of_first_purchases
from sales
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
I think that you are using COUNT() when you want SUM().
with first_purchases as
(select *,
case when is_first_purchase = 1 then 'Yes' else 'No' end as first_purchase
from sales)
select
SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
You could simplify your query as:
SELECT COUNT(*) AS
FROM sales no_of_first_purchases
WHERE is_first_purchase = 1
AND buyer_id = 456391
AND date_id BETWEEN '2021-02-01' AND '2021-03-01'
ORDER BY 1 DESC;
It is better to avoid the use of functions like IF and CASE when it can be done with WHERE.
The simplest approach for Trino (f.k.a. Presto SQL) is to use an aggregate with a filter:
count(name) FILTER (WHERE first_purchase = 'Yes') AS no_of_first_purchases

how to combine these two queries in a single query

How to combine these two queries into single query
1. select sum(amount) as received from voucher where amount>0
2. select sum(amount) as repaid from voucher where amount<0
You may use conditional aggregation
select sum( case when amount > 0 then amount else 0 end ) as received,
sum( case when amount < 0 then amount else 0 end ) as repaid
FROM t
You may use FILTER in Postgres 9.4 +
select sum( amount ) filter (where amount > 0 ) as received,
sum( amount ) filter (where amount < 0 ) as repaid
FROM t
Try this.,
select case when amount>0 then sum(amount) end as 'received',
case when amount<0 then sum(amount) end as 'repaid' from voucher

SQL statement selecting a count of a column

I have this SQL query:
SELECT
COUNT(SDDOCO) AS Total
FROM
KAIPRDDTA.F4211LA, KAIPRDDTA.Dates
WHERE
SDDRQJ = Day10
which returns a count of all the orders for today.
I am trying to get a second column so that I have this:
To get orders that are not completed would be: SDNXTR < '562'. How would I add this to my sql query so that I can accomplish this goal? Let me know if you need anymore information and thanks in advance for your responses.
You have two options here:
SELECT
COUNT(SDDOCO) AS Total,
SUM(CASE WHEN SDNXTR < '562' THEN 1 ELSE 0 END) AS Not_Finished_Yet_With_SUM,
COUNT(CASE WHEN SDNXTR < '562' THEN 1 ELSE NULL END) AS Not_Finished_Yet_With_COUNT,
FROM
KAIPRDDTA.F4211LA, KAIPRDDTA.Dates
WHERE
SDDRQJ = Day10
You can use case statement to count that SDNXTR < '562' values like below:
SELECT count(SDDOCO) as Total,
sum(case when SDNXTR < '562' then 1 else 0 end) as not_yet_finished
FROM KAIPRDDTA.F4211LA, KAIPRDDTA.Dates
WHERE SDDRQJ = Day10

Sql ISNULL condition in Sql Pivot and Sql case

I searched for many solutions on SO and elsewhere but couldn't quite understand how to write a query for my problem.
Anyway my query looks like below
SELECT * FROM
(
SELECT Id, Date, Name, Amount,
CASE
WHEN DATEDIFF(DAY,Date,GETDATE()) <=0
THEN 'Current'
WHEN DATEDIFF(DAY,Date,GETDATE()) <30
THEN 'Due30'
WHEN DATEDIFF(DAY,Date,GETDATE()) <60
THEN 'Due60'
ELSE 'Due90'
END AS [Age]
FROM Statement
WHERE (Amount <> 0)
) AS S
PIVOT
(
SUM(Amount)
FOR[Age] IN ([Current],[Due30],[Due60],[Due90])
) P
and the result looks like this
Id Date Name Current Due30 Due60 Due90
----------- ---------- --------------------------------------------
1 2016-04-03 Alan NULL NULL NULL 110.00
2 2016-05-02 TC NULL NULL 30.00 NULL
where should i insert IsNull condition to be able to remove the null in the result and add a zero there.
I tried inserting IsNull in the pivot query but we all know that is not meant to work
You have to add it repetitively in the final SELECT, when you replace the SELECT * (which should only exist in ad-hoc queries or EXISTS tests) with the column list:
SELECT
Id,
Date,
Name,
COALESCE([Current],0) as [Current],
COALESCE(Due30,0) as Due30,
COALESCE(Due60,0) as Due60,
COALESCE(Due90,0) as Due90
FROM
(
SELECT Id, Date, Name, Amount,
CASE
WHEN DATEDIFF(DAY,Date,GETDATE()) <=0
THEN 'Current'
WHEN DATEDIFF(DAY,Date,GETDATE()) <30
THEN 'Due30'
WHEN DATEDIFF(DAY,Date,GETDATE()) <60
THEN 'Due60'
ELSE 'Due90'
END AS [Age]
FROM Statement
WHERE (Amount <> 0)
) AS S
PIVOT
(
SUM(Amount)
FOR[Age] IN ([Current],[Due30],[Due60],[Due90])
) P
I've also used COALESCE since it's generally the preferred option (ANSI standard, extends to more than two arguments, applies normal type precedence rules) instead of ISNULL.
SELECT Id
, [Date]
, Name
, [Current] = SUM(CASE WHEN val <= 0 THEN Amount ELSE 0 END)
, Due30 = SUM(CASE WHEN val < 30 THEN Amount ELSE 0 END)
, Due60 = SUM(CASE WHEN val < 60 THEN Amount ELSE 0 END)
, Due90 = SUM(CASE WHEN val >= 60 THEN Amount ELSE 0 END)
FROM dbo.[Statement] t
CROSS APPLY (
SELECT val = DATEDIFF(DAY, [Date], GETDATE())
) s
WHERE Amount <> 0
GROUP BY Id, [Date], Name

SQL percentage with rows same table with different where condition

I want to do a query like:
select
count(asterisk) where acción='a'/count(asterisk) where acción='b' * 100
from
same_table
grouped by day
but I don't want use subquery, is it possible with joins?
I`m not sure the syntax is correct, but you can use something like this:
SELECT day,
SUM(CASE WHEN "acción" = 'a' THEN 1 ELSE 0 END) AS SUM_A,
SUM(CASE WHEN "acción" = 'b' THEN 1 ELSE 0 END) AS SUM_B,
SUM(CASE WHEN "acción" = 'a' THEN 1 ELSE 0 END) AS SUM_A / SUM(CASE WHEN "acción" = 'b' THEN 1 ELSE 0 END) * 100 AS result
FROM your_table
GROUP BY day
The concept is to actually sum the the values that you need, instead of count.