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

时间:2014-02-28 16:10:17

标签: mysql sql sql-server

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

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

以下是我的初始查询。我意识到这是完全错误的,但我尝试了许多不同的解决方案尝试,但似乎没有一个适合我的具体问题。我把它包括在内,以了解我的需求。行为与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

1 个答案:

答案 0 :(得分:2)

您可以使用带有聚合的CASE(至少在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')