繁体   English   中英

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

[英]SELECT from several tables with the same input (SQL SERVER 2005)

如何将几个结果集合并为一个。 假设我有这五个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?

一种方法是使用通用表表达式 ,然后交叉连接它们

    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... 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM