【问题标题】:SELECT from several tables with the same input (SQL SERVER 2005)从具有相同输入的多个表中选择 (SQL SERVER 2005)
【发布时间】:2011-12-13 00:51:55
【问题描述】:

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

【问题讨论】:

  • 如何将 A table1 加入到 table2 中,它们之间没有任何关系......或者你忘记了......?你没有表之间的外键
  • 真的不知道为什么我应该因为提出一个非常明确而具体的问题而被扣分......

标签: sql sql-server-2005 select


【解决方案1】:

一种方法是使用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... 

【讨论】:

    猜你喜欢
    • 2012-08-15
    • 1970-01-01
    • 2015-02-02
    • 2022-07-13
    • 2013-07-25
    • 2011-08-06
    • 1970-01-01
    • 2019-11-09
    • 2019-02-10
    相关资源
    最近更新 更多