【发布时间】:2014-02-28 16:10:16
【问题描述】:
我已尝试到处寻找答案,但没有人回答我的确切问题。我有什么应该是一个相对简单的查询。但是,我很新,还在学习 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
【问题讨论】:
-
您使用的是 MySQL 还是 SQL Server?请适当地标记问题。
-
SQL 服务器。为我未能标注而道歉。
标签: mysql sql sql-server