如何在同一个表中获取具有不同相同列值的DB记录

时间:2017-03-28 10:12:20

标签: sql sybase

请看下面的SQL:

SELECT TOP 3 acct_num from acct_package
where package_key IN 
(
  select package_key from acct_serv 
  where serv_id  = 'A1'
  and package_key IN (                                                    
                        select package_key from acct_serv 
                        where serv_id  = 'B1'
                        and package_key IN(
                                            select package_key from acct_serv 
                                            where serv_id  = 'C1' 
                                          )
                     )
)

如果没有其他表格有关系。

我可以通过上面的SQL检索我需要的数据,但我想其他编码可能更有效。

非常感谢帮助!!!

2 个答案:

答案 0 :(得分:1)

这是另一种方法(请记住在使用TOP xx时使用ORDER BY,否则结果是不可预测的)(我在Oracle DB上尝试过,当然没有TOP):

SELECT TOP 3 ACCT_NUM 
FROM ACCT_PACKAGE A
INNER JOIN (SELECT PACKAGE_KEY, SUM(RC) AS SUM_TOT
            FROM (SELECT PACKAGE_KEY, SERV_ID, 1 AS RC
                  FROM ACCT_SERV
                  WHERE SERV_ID IN ('A1','B1','C1')
                  GROUP BY PACKAGE_KEY, SERV_ID      
                  ) B 
            GROUP BY PACKAGE_KEY
            ) C ON A.PACKAGE_KEY = C.PACKAGE_KEY
WHERE SUM_TOT >=3   
ORDER BY A.PACKAGE_KEY;

答案 1 :(得分:0)

str