从具有相同输入的多个表中进行SELECT(SQL SERVER 2005)

时间:2011-10-22 04:52:04

标签: sql sql-server-2005 select

如何将几个结果集合并为一个。假设我有这五个sql选择,它们都采用相同的“简单”输入(10):

SELECT agentid, latitude, longitude, availability, updated
FROM table1
WHERE agentid=10

SELECT email, name, phone, company
FROM table2
WHERE userid=10

SELECT COUNT(*) AS pt1num
FROM table3
WHERE agentid=10 AND propertytype<6

SELECT COUNT(*) AS pt2num
FROM table3
WHERE agentid=10 AND propertytype>6 AND propertytype<9

SELECT COUNT(*) AS pt3num
FROM table3
WHERE agentid=10 AND propertytype>8

如何UNION或JOIN或子查询,以便我获得包含所有列的行; agentid,纬度,经度,可用性,更新,电子邮件,名称,电话,公司,pt1num,pt2num,pt3num?

1 个答案:

答案 0 :(得分:6)

一种方法是使用Common table expressions,然后交叉加入

    with cte1 as ( 
    SELECT agentid, latitude, longitude, availability, updated
    FROM table1
    WHERE agentid=10)
    , cte2 as (

    SELECT email, name, phone, company
    FROM table2
    WHERE userid=10)

    , cte3 as (
    SELECT COUNT(*) AS pt1num
    FROM table3
    WHERE agentid=10 AND propertytype<6)

    , cte4 as (SELECT COUNT(*) AS pt2num
    FROM table3
    WHERE agentid=10 AND propertytype>6 AND propertytype<9)

    ,  cte5 as (
    SELECT COUNT(*) AS pt3num
    FROM table3
    WHERE agentid=10 AND propertytype>8)


SELECT [youfieldlist] 
FROM 
  cte1, cte2, cte3, cte4, cte5

另一种方法是使用内联视图

Select [your field list]
FROM (
SELECT agentid, latitude, longitude, availability, updated
FROM table1
WHERE agentid=10 ) t1,
(
SELECT email, name, phone, company
FROM table2
WHERE userid=10) t2, 
(
SELECT COUNT(*) AS pt1num
FROM table3
WHERE agentid=10 AND propertytype<6) t3,
(
SELECT COUNT(*) AS pt2num
FROM table3
WHERE agentid=10 AND propertytype>6 AND propertytype<9) t4,
(
SELECT COUNT(*) AS pt3num
FROM table3
WHERE agentid=10 AND propertytype>8) t5

如果您知道每个选择只返回一行

,这些只是非常合理

您还可以使用局部变量进行每次选择

DECLARE @agentid int, @latitude int , ... 
SELECT   @agentid = agentid,  @latitude = latitude, ...
        FROM table1
        WHERE agentid=10

DECLARE @pt1num int
 SELECT @pt1num  = COUNT(*)  
    FROM table3
    WHERE agentid=10 AND propertytype<6

然后选择它们

SELECT  @agentid agentid,  @latitude latitude, ... @pt1num...