从一列中仅选择不同的值

时间:2014-03-17 03:41:33

标签: sql select distinct sybase sybase-ase

我在查询中显示三个字段,我想显示一个不同的banking_no。我仍然希望显示其他字段,即使它们并不明显。请帮忙。

SELECT  C.RECEIPT_OFFICE_PREFIX, B.BANKING_NO, B.STATUS_CD
FROM    TControl B, TComponent C
WHERE   C.DEPOSIT_BANK_ACCT = 'xxx-xxxxxx-xxxxx'
AND     B.BANKING_NO = C.BANKING_NO
AND     B.COMPANY_ID = C.COMPANY_ID
AND     B.RECEIPT_OFFICE_PREFIX = C.RECEIPT_OFFICE_PREFIX
AND     B.STATUS_CD != 'C'
ORDER BY B.BANKING_NO

我正在使用Sybase ASE 12.5

2 个答案:

答案 0 :(得分:0)

最新版本的Sybase支持row_number()。你可以在这样的子查询中使用它:

SELECT RECEIPT_OFFICE_PREFIX, BANKING_NO, STATUS_CD
FROM (SELECT C.RECEIPT_OFFICE_PREFIX, B.BANKING_NO, B.STATUS_CD,
             ROW_NUMBER() OVER (PARTITION BY B.BANKING_NO ORDER BY B.BANKING_NO) as seqnum
      FROM TControl B JOIN
           TComponent C
           ON B.BANKING_NO = C.BANKING_NO AND B.COMPANY_ID = C.COMPANY_ID
      WHERE C.DEPOSIT_BANK_ACCT = 'xxx-xxxxxx-xxxxx' AND     
            B.RECEIPT_OFFICE_PREFIX = C.RECEIPT_OFFICE_PREFIX AND
            B.STATUS_CD != 'C'
    ) BC
WHERE seqnum = 1
ORDER BY BANKING_NO;

答案 1 :(得分:0)

你想要什么可能不会被称为distint。如果剩下的数据是相同的,只需使用DISTINCT即可。但是,如果数据可能不同,您需要告诉数据库应该选择什么结果。第一排?最后一排?

如果你不介意只使用;

SELECT DISTINCT  MAX(C.RECEIPT_OFFICE_PREFIX), B.BANKING_NO, MAX(B.STATUS_CD)
FROM    TControl B, TComponent C
WHERE   C.DEPOSIT_BANK_ACCT = 'xxx-xxxxxx-xxxxx'
AND     B.BANKING_NO = C.BANKING_NO
AND     B.COMPANY_ID = C.COMPANY_ID
AND     B.RECEIPT_OFFICE_PREFIX = C.RECEIPT_OFFICE_PREFIX
AND     B.STATUS_CD != 'C'
GROUP BY B.BANKING_NO

你需要选择一行使用Gordon解决方案。