SQL单行查询建议

时间:2017-09-08 01:27:21

标签: sql sql-server select

我可以请求我的SQL报告查询帮助,我90%只需要最后一步(仍然学习SQL,所以要善待:))。

我们目前有2个不同的数据库:
- [DATABASE1]存储我们的所有资产
- [DATABASE2]存储我们仍在还清的所有资产 - - 该数据库将每项针对资产的付款存储到银行,付款日期,金额等 - - 资产的最后一行将是最后一笔付款,而此日期将是预期的租约结束日期。

我想要一个报告,每个资产都有一行显示所有列 我当前的报告显示了所有必需的信息,但它显示了每个资产的所有行而不是单个封装的行,例如:

ASSET NO | FINANCIER | AGEEMENT NUMBER | PAYMENT NUMBER | LEASE COMMENCE DATE | LEASE FINAL DATE | MONTHLY PAYMENTS
asset1 | bank 1 | 1111 | 1 | 01/01/2017 | NULL | NULL
asset1 | bank 1 | 1111 | 2 | NULL | NULL | 2000
asset1 | bank 1 | 1111 | 3 | NULL | NULL | NULL
..
asset1 | bank 1 | 1111 | 20 | NULL | 01/01/2020 | NULL
asset2 | bank 5 | 1536 | 1 | 05/08/2016 | NULL | NULL
..

而不是:

ASSET NO | FINANCIER | AGEEMENT NUMBER | PAYMENT NUMBER | LEASE COMMENCE DATE | LEASE FINAL DATE | MONTHLY PAYMENTS
    asset1 | bank 1 | 1111 | 20 | 01/01/2017 | 01/01/2020 | 2000
    asset2 | bank 5 | 1536 | 15 | 05/08/2016 | 12/05/2019 | 5500
    ..

以下是我的询问:

Declare @MaxPays TABLE (
    ITEMNO VARCHAR(MAX),
    PAYNO VARCHAR(MAX)
)

INSERT INTO @MaxPays
SELECT
    a.ITEMNO,
    a.PAYNO
FROM 
    [DATABASE1] a
INNER JOIN 
    (SELECT ITEMNO, MAX(PAYNO) as PAYNO FROM [DATABASE1] GROUP BY ITEMNO) AS b ON
    a.ITEMNO = b.ITEMNO AND a.PAYNO = b.PAYNO

SELECT
    a.ITEMNO as 'Asset #',
    a.FINANCE as 'Financier',
    a.AGREENO as 'Agreement number',
    a.PAYNO as 'Payment Number',
        CASE WHEN a.PAYNO = 1 THEN a.PAYDATE ELSE NULL END as 'Lease Commencing Date',
        CASE WHEN a.PAYNO = (SELECT PAYNO FROM @MaxPays WHERE ITEMNO = a.ITEMNO) THEN a.PAYDATE ELSE NULL END as 'Lease Finalising Date',
        CASE WHEN a.PAYNO = 2 THEN a.PAYAMOUNT ELSE NULL END as 'Monthly Payments'
FROM 
    [DATABASE1] a
INNER JOIN 
    (SELECT DISTINCT ITEMNO from [DATABASE2]) AS b ON
    a.ITEMNO = b.ITEMNO
ORDER BY a.ITEMNO

编辑:每月付款链接到第二个实例,因为有时第一笔付款包含预付款,并且不是每月定期付款的明确指标

任何帮助都将不胜感激。

由于

1 个答案:

答案 0 :(得分:0)

您只需要对查询进行微小修改 -

SELECT
a.ITEMNO as 'Asset #',
a.FINANCE as 'Financier',
a.AGREENO as 'Agreement number',
a.PAYNO as 'Payment Number',
MAX(CASE WHEN a.PAYNO = 1 THEN a.PAYDATE ELSE NULL END) as 'Lease Commencing Date',
MAX(CASE WHEN a.PAYNO = (SELECT PAYNO FROM @MaxPays WHERE ITEMNO = a.ITEMNO) THEN a.PAYDATE ELSE NULL END) as 'Lease Finalising Date',
MAX(CASE WHEN a.PAYNO = 2 THEN a.PAYAMOUNT ELSE NULL END) as 'Monthly Payments'
FROM 
[DATABASE1] a
INNER JOIN 
(SELECT DISTINCT ITEMNO from [DATABASE2]) AS b ON
a.ITEMNO = b.ITEMNO
GROUP BY a.ITEMNO,
         a.FINANCE,
         a.AGREENO,
         a.PAYNO,
ORDER BY a.ITEMNO