小编典典

SQL-在where子句中用不同的日期两次查询同一列

sql

我尝试遍地寻找答案,但没有一个人回答我的确切问题。我有什么应该是一个相对简单的查询。但是,我很新,仍然在学习SQL。
我需要查询具有不同日期的两列。我想返回具有当前帐户数和当前未结余额的行,并且在同一查询中,返回具有90天前数据的同一列的行。这样,我们可以看到过去90天内帐户和余额的数量增加了多少。理想情况下,我正在寻找这样的结果:

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

以下是我的开始查询。我意识到这是完全错误的,但是我尝试了许多不同的解决方案尝试,但是似乎都无法解决我的特定问题。我将其包括在内可以让我对自己的需求有所了解。accts&AcctBal列将包含1/31/14数据。PriorAcct和PriorBal列将包含10/31/13数据。

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

阅读 214

收藏
2021-05-30

共1个答案

小编典典

您可以CASE为此使用a和聚合(至少在SQL Server中,不确定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')
2021-05-30