Sql-Server
對另一個查詢的結果執行查詢?
我有 2 個查詢,它們都執行良好並提取了我正在尋找的結果。但是,我需要能夠從另一個結果中執行一個查詢。這是 t-sql/mssql/sybase
例如,以下查詢用於計算每個值在 case 表的“referred_link”列中顯示的次數/行數,並僅顯示出現 3 次或更多次的那些:
SELECT cases.referred_link, count(*) FROM CASES GROUP BY referred_link HAVING COUNT(*) >= 3
下一個查詢從各種表中提取一堆數據並根據所需條件進行過濾。問題是,我只希望第二個查詢在第一個查詢的結果上執行…在referred_link 表上顯示 3 次以上的項目。
select * from cases inner join names on cases.referred_link=names.names_id left join (select * from mailing_list_defined where mailing_list='home_addr') a on names.names_id=a.names_id left join party on cases.casenum=party.case_id where names.person='Y' and date_opened>=today()-6 and party.our_client='Y' and party.role='Plaintiff'
我嘗試過這樣的事情(當然不起作用):
select * from cases inner join names on cases.referred_link=names.names_id left join (select * from mailing_list_defined where mailing_list='Mattar Stars') a on names.names_id=a.names_id left join party on cases.casenum=party.case_id where names.person='Y' and date_opened>=today()-6 and party.our_client='Y' and party.role='Plaintiff' and names_id IN (SELECT cases.referred_link, count(*) FROM CASES GROUP BY referred_link HAVING COUNT(*) >= 3)
任何人都可以為我指出如何實現這一目標的正確方向嗎?
當您在 IN(…) 之間放置子查詢時,您必須確保它只返回一列。通過您的其他查詢,似乎cases.referred_link實際上已經是names_id,所以您已經差不多了。您需要做的就是從選定列的列表中刪除額外的計數(*)。
… and names.names_id IN (SELECT cases.referred_link FROM CASES GROUP BY referred_link HAVING COUNT(*) >= 3)
那麼如果你使用一個簡單的 會發生什麼
JOIN
呢?該JOIN
條件很可能是錯誤的,因為我不知道哪些列連結了 2 個查詢。SELECT * FROM ( SELECT cases.referred_link, count(*) FROM CASES GROUP BY referred_link HAVING COUNT(*) >= 3 ) cnt JOIN ( select * from cases inner join names on cases.referred_link=names.names_id left join (select * from mailing_list_defined where mailing_list='home_addr') a on names.names_id=a.names_id left join party on cases.casenum=party.case_id where names.person='Y' and date_opened>=today()-6 and party.our_client='Y' and party.role='Plaintiff' ) data ON data.names_id = cnt.referred_link