I have a table with name loan_emi. I want select last emi payment date, last emi date, total no. of emi, no. of paid emi and no. of unpaid emi. here is my query.
SELECT MAX(emi_date)AS pay_date,
(SELECT MAX(emi_date) FROM loan_emi WHERE l_id=a.l_id AND is_paid=0
)AS last_date,
(SELECT COUNT(id) FROM loan_emi WHERE l_id=a.l_id
)AS tenor,
(SELECT COUNT(id) FROM loan_emi WHERE l_id=a.l_id AND is_paid=1
)AS paid,
(SELECT COUNT(id) FROM loan_emi WHERE l_id=a.l_id AND is_paid=0
)AS unpaid
FROM loan_emi a
WHERE id =" + lId + "
AND is_paid=1 GROUP BY l_id
But here is multiple sub queries. Please help me to simplify that. Thanks in advance.
just put into a single query with a case/when for each field. This way it is one pass for all the records for the ID in question, no joins, no subqueries. Also, as I have it, you probably want to PARAMETERIZE your query where indicated for the ID of the account in question...
SELECT
MAX( case when is_paid = 1 then emi_date else null end ) as Pay_Date,
MAX( case when is_paid = 0 then emi_date else null end ) as Last_Date,
COUNT(*) as Tenor,
SUM( case when is_paid = 1 then 1 else 0 end ) as Paid,
SUM( case when is_paid = 0 then 1 else 0 end ) as Unpaid
from
loan_emi
where
id = ?ParameterizeYourIncomingID
group by
l_id
Related
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
I have a table on hand:
order_id, order_status (2=completed, 1=canceled), client_id, fee
I need to find how many client completed 1 order, and how many client completed more than 1 order.
I tried case as below but no clue:
select client_id, count(case order_status when '2' then 'completed' end) as cnt_completed, sum(fee)
from order
where cnt_completed = 1;
Are there any straightforward ways to get the numbers of clients who completed 1 order and numbers of clients who completed more than 1 order, along with the sum of fee for each group? Thanks.
Use two levels of aggregation to get this broken out by the number of orders:
select cnt, count(*), sum(sum_fee)
from (select client_id, count(*) as cnt, sum(fee) as sum_fee
from order o
where order_status = '2'
group by client_id
) o
group by cnt;
For just two rows, you can use:
select (case when cnt = 1 then 1 else 2 end), count(*), sum(sum_fee)
from (select client_id, count(*) as cnt, sum(fee) as sum_fee
from order o
where order_status = '2'
group by client_id
) o
group by (case when cnt = 1 then 1 else 2 end);
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
I have table that contain Id,Date and Status i.e open/close
i just want a result in sql that contain month wise open,close and total count of Id's
e.g In Jan open count 15,close count 5 and total count 20
Use RollUp() and Group By as below:
;WITH T AS
(
SELECT
Id,
DATENAME(MONTH,[Date]) AS [MonthName],
Status
FROM #tblTest
)
SELECT
[MonthName],
[Status],
StatusCount
FROM
(
SELECT
MonthName,
CASE ISNULL(Status,'') WHEN '' THEN 'Total' ELSE Status END AS Status,
Count(Status) AS StatusCount
FROM T
GROUP BY ROLLUP([MonthName],[Status])
)X
WHERE X.MonthName IS NOT NULL
ORDER BY X.[MonthName],X.[Status]
Output:
Note: If required data in single row by month then apply PIVOT
select year(date), month(date),
sum(case when status = 'open' then 1 else 0 end) as open_count,
sum(case when status = 'closed' then 1 else 0 end) as closed_count,
count(*) as total_count
from your_table
group by year(date), month(date)
I use the following
select TotalCredits - TotalDebits as Difference
from
(
select
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits,
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits
) temp
this returns one field with my difference, the problem i am occuring is that if the table has no credit, but has debits, the temp table contains a NULL value in the TotalCredits Field which prohibts math being done. (Vica Versa on has Credits but no Debits) I have tried coalese but cant seem how to make it work.
rationally i need to check if:
sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1 as TotalCredits is
null then totalcredits = 0 and visa versa
sql server 2008
select ISNULL(TotalCredits,0) - ISNULL(TotalDebits,0) as Difference
from
(
select
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits,
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits
) temp
Change your query to conditional aggregation and it fixes the problem:
select sum(case when credit = 1 then TotalAmount else -TotalAmount end) as Difference
from Journal
where memberid = 48 and (credit = 1 or debit = 1);
EDIT:
If you have the case where credit and debit could both be 1, then use:
select (sum(case when credit = 1 then TotalAmount else 0 end) -
sum(case when debit = 1 then TotalAmount else 0 end)
) as Difference
from Journal
where memberid = 48 and (credit = 1 or debit = 1);
Hello may be this can also can give the expected result
select COALESCE(TotalCredits,0) - COALESCE(TotalDebits,0) as Difference
from
(
select
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits,
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits
) temp
Create a sub query using isnull to replace the null with 0 and then make the sum querys and then the total substraction
Ouch. That query makes my head hurt. Discriminant functions are your friend and case lets you create them easily in SQL. Just state the problem simply.
select total_credits = sum( case j.credit when 1 then 1 else 0 end ) ,
total_debits = sum( case j.debit when 1 then 1 else 0 end ) ,
total_delta = sum( case j.credit when 1 then 1 else 0 end )
- sum( case j.debit when 1 then 1 else 0 end )
from journal j
where j.memberid = 48