需要使用连接查询仅提取一行

时间:2014-05-29 05:30:36

标签: sql-server sql-server-2008

我试图从连接表X和表Y中提取一条记录。

以下是使用

的查询
SELECT  (select ACCOUNTSALESFORCEDETAILID
        FROM    sysdba.ACCOUNTSALESFORCEDETAIL AS a1
        WHERE   ORGSALESFORCEID = 'QWKHAA000STK' 
        AND     ACCOUNTID = O.ACCOUNTID
        and     MODIFYDATE =    (
                                SELECT  MIN(MODIFYDATE) AS MODIFYDATE
                                FROM    sysdba.ACCOUNTSALESFORCEDETAIL
                                WHERE   ACCOUNTID = a1.ACCOUNTID
                                AND     ORGSALESFORCEID = a1.ORGSALESFORCEID
                                GROUP   BY ACCOUNTID, ORGSALESFORCEID
                                )
        ),
        a.ORGSALESFORCEID
FROM    sysdba.ACCOUNTSALESFORCEDETAIL a  
JOIN    sysdba.ACCOUNT O on a.ACCOUNTID=O.ACCOUNTID 
WHERE   O.ACCOUNTID ='A61E6C43EE71' 
AND     A.ORGSALESFORCEID in ('QWKHAA000STK','QWKHAA01KXNC','QWKHAA01KXNE')

下面是我现在得到的结果:

ACCOUNTSALESFORCEID       ORGSALESFORCEID
QB46AC89800B              QWKHAA000STK
QB46AC89800B              QWKHAA01KXNC
QB46AC89800B              QWKHAA01KXNE

但我只需要第一行作为输出..

请帮忙。

1 个答案:

答案 0 :(得分:0)

尝试这样

SELECT TOP(1) col1,ORGSALESFORCEID
FROM
(SELECT
   (
    SELECT    
        ACCOUNTSALESFORCEDETAILID
    FROM    
        sysdba.ACCOUNTSALESFORCEDETAIL AS a1
    WHERE  (ORGSALESFORCEID = 'QWKHAA000STK') 
        AND  (ACCOUNTID=O.ACCOUNTID) 
        AND (MODIFYDATE =(  SELECT     MIN(MODIFYDATE) AS MODIFYDATE
                            FROM     sysdba.ACCOUNTSALESFORCEDETAIL
                            WHERE      (ACCOUNTID = a1.ACCOUNTID) AND (ORGSALESFORCEID=a1.ORGSALESFORCEID)
                            GROUP BY ACCOUNTID, ORGSALESFORCEID)
            )
    ) AS col1
    ,a.ORGSALESFORCEID

FROM 
    sysdba.ACCOUNTSALESFORCEDETAIL a  JOIN sysdba.ACCOUNT O on a.ACCOUNTID=O.ACCOUNTID 
WHERE O.ACCOUNTID='A61E6C43EE71' and   A.ORGSALESFORCEID in ('QWKHAA000STK','QWKHAA01KXNC','QWKHAA01KXNE')
) AS temp