SQL:过滤两个列值的组合

时间:2009-03-12 02:01:10

标签: sql sybase

我有一个表balances,其中包含以下列:

bank | account | date | amount

我还有一个accountsbank作为其复合主键。

我想进行类似以下伪代码的查询:

account

银行账户对列表由客户提供。 我该怎么做呢?创建一个临时表并加入它?

我正在使用Sybase

4 个答案:

答案 0 :(得分:2)

获得更多信息可能会有所帮助。

如果您有标准推动您的特定银行和帐户实体列表,那么您应该加入这些表。

你有银行表和账户表吗?

假设您在accounts表中有信息缩小了您想要引用的特定帐户,例如假设您的Accounts表有一个IsActive char(1)NOT NULL字段,并且您希望您将写入非活动帐户的余额像这样的东西:

SELECT date, sum( amount ) AS amount
FROM Balances b 
     INNER JOIN Accounts a 
     ON b.Bank = a.Bank AND b.Account = a.Account
WHERE a.IsActive = 'N'

从设计的角度来看,您应该创建一个人工密钥来删除跨表的非标识数据的复制。这会给你这样的东西:

CREATE TABLE Accounts ( 
    AccountId int identity(1,1) NOT NULL,
    Bank nvarchar(15) NOT NULL,
    Account nvarchar(15) NOT NULL
)

CREATE TABLE Balances ( 
    AccountId int,
    Date datetime, 
    Amount money
)

这样可以编辑银行或帐户字段中的错误,而无需将这些更改级联到余额表以及稍微简单的查询。

SELECT date, sum( amount ) AS amount
FROM Balances b 
     INNER JOIN Accounts a 
     ON b.AccountId = a.AccountId
WHERE a.IsActive = 'N'

答案 1 :(得分:2)

如果在您的应用中已知银行帐户对,您只需写下:

(bank = 1 AND account = 2) OR (bank = 3 AND account = 4) OR ...

如果银行账户对的列表是子查询,那么写下这样的内容:

SELECT * FROM balances b LEFT JOIN bank_account_pairs p ON ...
WHERE b.bank = p.bank AND b.account = p.account AND ...

答案 2 :(得分:0)

内部联接会强制执行银行+帐户组合,但您必须小心获得比预期更多的行,尤其是在进行总结时。

以下内容可能会起作用,但它取决于Sybase是否支持

select b.date, sum(b.amount) as amount
from balances as b
where exists (select 1 from backaccounts as ba where ba.bank = b.bank and ba.account = b.account)
group by b.date

答案 3 :(得分:0)

如果你不想做一个临时表,一个解决方案就是这样:

select bank, account, sum(amount)
from balances,
(select 'XXX' as bank, 13232 as account
  union all
 select 'YYY' as bank, 138232 as account
  union all
 select 'ZZZ' as bank, 183823 as account) banks
where balances.bank = banks.bank
  and balances.account = banks.account

如果你的应用可以处理它,最好的选择可能是这样的:

select bank, account, sum(amount)
from balances
where (bank = 'XXX' and account = 123i832)
    or (bank = 'YYY' and account = 28323)
    or (bank = 'ZZZ' and account = 2839283)