SQL查询加入

时间:2012-02-12 23:10:21

标签: sql sql-server tsql sql-server-2000

我有以下数据集:

ID   PeriodID    Account     Amount  
1    1000        Y0001       100.00  
2    1000        M0001       20.00  
3    1000        Y0002       75.00  
4    1000        M0002       15.00  
5    1000        Y0003       100.00  
6    1000        Y0004       200.00  

我需要编写一个返回零的查询,有一个“Y”帐户,没有“M”帐户,例如:

PeriodID    Account     Amount  
1000        Y0001       100.00  
1000        M0001       20.00  
1000        Y0002       75.00  
1000        M0002       15.00  
1000        Y0003       100.00  
1000        Y0003       0.00  
1000        Y0004       200.00 
1000        Y0004       0.00 

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

也许不是最有效的方法,但这应该可以帮到你找到你想要的东西:

SELECT PeriodID, Account, Amount
FROM myTable

UNION ALL

SELECT PeriodID, Account, 0.00 AS Amount
FROM myTable A
WHERE NOT EXISTS (
    SELECT * FROM myTable B 
    WHERE B.Account = 'M' + SUBSTRING(A.Account, 2, LEN(A.Account) - 1)
)

答案 1 :(得分:1)

另一种方法,假设帐户在一个时期内是唯一的:

SELECT m1.PeriodID
    , COALESCE(CASE WHEN at.AccountType = 'Y' then m1.Account end, m2.Account, m1.Account) as Account
    , COALESCE(CASE WHEN at.AccountType = 'Y' then m1.Amount end, m2.Amount, 0.00) as Amount
FROM myTable m1
    LEFT OUTER JOIN myTable m2
        ON m2.PeriodID = m1.PeriodID
        AND m2.ACCOUNT = STUFF(m1.Account, 1, 1, 'M')
    CROSS JOIN (SELECT 'Y' as AccountType UNION ALL SELECT 'M') at
WHERE m1.Account LIKE 'Y%'
ORDER BY m1.PeriodID, m1.Account, at.AccountType DESC