从具有相同输入的多个表中选择(SQL SERVER 2005)
如何将两个结果集合并为一个。假设我有五个sql选择,它们都采用相同的“简单”输入(10):从具有相同输入的多个表中选择(SQL SERVER 2005),sql,sql-server-2005,select,Sql,Sql Server 2005,Select,如何将两个结果集合并为一个。假设我有五个sql选择,它们都采用相同的“简单”输入(10): 选择代理、纬度、经度、可用性、已更新 来自表1 其中agentid=10 选择电子邮件、姓名、电话、公司 来自表2 其中userid=10 选择COUNT(*)作为pt1num 来自表3 其中agentid=10,propertytype6和propertytype8 如何联合、联接或子查询,以便获得包含所有列的行;agentid、纬度、经度、可用性、更新、电子邮件、姓名、电话、公司、pt1num、pt
选择代理、纬度、经度、可用性、已更新
来自表1
其中agentid=10
选择电子邮件、姓名、电话、公司
来自表2
其中userid=10
选择COUNT(*)作为pt1num
来自表3
其中agentid=10,propertytype6和propertytype8
如何联合、联接或子查询,以便获得包含所有列的行;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
一种方法是使用它们,然后交叉连接它们
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
你怎么能把一个表1连接到一个表2,而这个表1和表2之间没有关系。。还是你忘了。。?表之间没有外键吗?我真的不知道为什么我问了一个非常明确和具体的问题就应该得到一个负号…你怎么能把一个表1连接到一个与表2没有关系的表2。。还是你忘了。。?我真的不知道为什么我问了一个非常明确和具体的问题就应该得到一个负号。。。
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...