SQL-在where子句中用不同的日期两次查询同一列
技术问答
251 人阅读
|
0 人回复
|
2023-09-12
|
我试图到处寻找答案,但没有人回答我确切的问题。我应该做一个相对简单的查询。但是,我很新,还在学习SQL。
- d, e* W& r! N2 r0 T我需要查询两个不同日期的列。我想返回具有当前账户数量和当前未结算余额的银行,并在同一查询中返回具有90天前数据的银行。这样,我们就可以看到过去90天账户和余额增加了多少。理想情况下,我正在寻找这样的结果:" i! q& @; i# O4 P
PropCode|PropCat|Accts|AcctBal|PriorAccts|PriorBal|---------------------------------------------------- |Comm | 350 | 1,000| | 750以下是我的开始查询。我意识到这是完全错误的,但我尝试了很多不同的解决方案,但似乎解决不了我的具体问题。我可以让我知道我的需求,包括它。accts&AcctBal列将包含1/31/14数据。PriorAcct和PriorBal列将包含10/31/13数据。
5 ^7 x8 y0 |5 e4 p9 i9 `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 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,) AS PriorBalfrom table1where 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 group by prop_code,prop_catorder by prop_cat
% p, q& G3 K C 解决方案:
5 V8 |' Z, B' t6 f8 s0 M% k 您可以CASE为此使用a和聚合(至少在SQL Server中,不确定MySQL):* p. L9 v* d0 W! b6 E
...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 |
|
|
|
|
|