Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Query same column twice with different dates in where clause

I have tried searching all over for answers but none have answered my exact issue. I have what should be a relatively simple query. However, I am very new and still learning SQL.
I need to query two columns with different dates. I want to return rows with the current number of accounts and current outstanding balance and in the same query, return rows for the same columns with data 90 days prior. This way, we can see how much the number of accounts and balance increased over the past 90 days. Optimally, I am looking for results like this:

PropCode|PropCat|Accts|AcctBal|PriorAccts|PriorBal|
----------------------------------------------------
 77     |Comm   | 350 | 1,000|  275      | 750

Below is my starting query. I realize it's completely wrong but I have tried numerous different solution attempts but none seem to work for my specific problem. I included it to give an idea of my needs. The accts & AcctBal columns would contain the 1/31/14 data. The PriorAcct & PriorBal columns would contain the 10/31/13 data.

select 
prop_code AS PropCode,
prop_cat, 
COUNT(act_num) Accts,
SUM(act_bal) AcctBal,

(SELECT 
COUNT(act_num) 
FROM table1 
where date = '10/31/13'
and Pro_Group in ('BB','FF') 
and prop_cat not in ('retail', 'personal') 
and Not (Acct_Code = 53 and ACTType in (1,2,3,4,5,6,7)) 
) 
AS PriorAccts,

(SELECT 
SUM(act_bal) 
FROM table1 
where date = '10/31/13'
and Pro_Group in ('BB','FF') 
and prop_cat not in ('retail', 'personal') 
and Not (Acct_Code = 53 and ACTType in (1,2,3,4,5,6,7)) 
) 
AS PriorBal


from table1
where date = '01/31/14'
and Pro_Group in ('BB','FF') 
and prop_cat not in ('retail', 'personal') 
and Not (Acct_Code = 53 and ACTType in (1,2,3,4,5,6,7)) 
group by prop_code, prop_cat
order by prop_cat
like image 796
Jay H. Avatar asked Jan 22 '26 14:01

Jay H.


1 Answers

You can use a CASE with aggregates for this (at least in SQL Server, not sure about MySQL):

...
COUNT(CASE WHEN date='1/31/14' THEN act_num ELSE NULL END) as 'Accts'
,SUM(CASE WHEN date='1/31/14' THEN act_bal ELSE NULL END) as 'AcctBal'
,COUNT(CASE WHEN date='10/31/13' THEN act_num ELSE NULL END) as 'PriorAccts'
,SUM(CASE WHEN date='10/31/13' THEN act_bal ELSE NULL END) as 'PriorAcctBal'
....
WHERE Date IN ('1/31/14', '10/31/13')
like image 74
JNK Avatar answered Jan 25 '26 02:01

JNK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!