1

我花了几个小时试图解决这个问题,但遇到了很多挫折,但没有任何结果。我是这方面的新手,但愿意学习。我正在使用 SQLiteStudio

数据:

  1. 我有一张表,上面有一年的租金数据。
  2. 有租约的客户每周有一个条目(一些租约在一年内开始和/或结束,因此出现的次数可能少于 52 次
  3. 每周数据从不同的报告导入到此表中,并通过报告名称(字段:ReportName)进行区分
  4. 客户可以将状态从 CUR(当前)更改为 TER(终止 = 4 周通知)到 FOR(以前)
  5. 每个客户都有一个唯一的租赁参考号(字段:TenancyRef)

我的查询:

所以这个查询工作得很好/很好:

SELECT TenancyRef,
PropertyType,
TenancyType,
ManagementArea,
count() AS NumberEntries,
Round(Sum(Payments), 2) AS TotalPaid,
Round(Sum(HBUCAmount), 2) AS TotalHB,
Round(Sum(DebitAmount), 2) AS DebitTotal,
Round(Round(Sum(DebitAmount), 2) - Round(Sum(HBUCAmount), 2), 2) AS mySubtraction
FROM PSEData15
WHERE PropertyType != "LOCK" AND
PropertyType != "GP"
GROUP BY TenancyRef
HAVING TotalPaid = 0 AND
DebitTotal > TotalHB
ORDER BY TenancyRef DESC

它给了我一份清单,列出了这些客户支付了 0 英镑的近 900 份参考资料。

如果我单独运行此查询:

SELECT TenancyRef, Status, ClosingBal
FROM PSEData15
WHERE (ReportName = "PSE-W201552030416" OR ReportName = "PSE-F201552030416") AND
Status != "FOR" AND
PropertyType != "LOCK" AND
PropertyType != "GP" AND
ClosingBal > 0

它给了我上周所有当前客户及其期末余额(其中 3667 个)

目标:

基本上我正在寻找的是要添加到第一个查询的期末余额和 wk52 状态。任何帮助将不胜感激。先感谢您

编辑1:

我被要求提供样本数据和期望的结果。简化表格我的样本将是:

TenancyRef | Status | Payments | Closing Bal | ReportName
1          | CUR    | 0.00     | 10.00       | 2015-Wk49
1          | CUR    | 0.00     | 20.00       | 2015-Wk50
1          | CUR    | 0.00     | 30.00       | 2015-Wk51
1          | CUR    | 0.00     | 40.00       | 2015-Wk52
2          | CUR    | 10.00    | 20.00       | 2015-Wk49
2          | CUR    | 10.00    | 20.00       | 2015-Wk50
2          | TER    | 10.00    | 20.00       | 2015-Wk51
2          | FOR    | 10.00    | 20.00       | 2015-Wk52
3          | CUR    | 10.00    | 20.00       | 2015-Wk49
3          | TER    | 10.00    | 20.00       | 2015-Wk50
3          | FOR    | 10.00    | 20.00       | 2015-Wk51

期望的结果:

TenancyRef | Count  | TotalPaid | Wk52_ClosingBal | Wk52_status
1          | 4      | 0.00      | 40.00           | CUR
2          | 4      | 40.00     | 20.00           | FOR
3          | 3      | 30.00     | 20.00           | FOR
4

1 回答 1

1

If everyone has a Week52 report row, it's pretty simple, just add

max(case when reportname = '2015-Wk52' then ClosingBal else null end) as Week52ClosingBal,
max(case when reportname = '2015-Wk52' then Status else null end) as Week52Status

to your first query.

If, on the other hand, you need to determine the last status for a customer (ie not all of them have a Week52 report):

  1. Write a query which returns the last reportname that you want (given your filters) for each tenancyref.
  2. Join that query to your first query on tenancyref.
  3. Change the above conditional aggregates to max(case when reportname = joinedTable.reportname ... )
于 2016-05-16T20:20:43.947 回答