[英]SELECT from several tables with the same input (SQL SERVER 2005)
How do I combine a couple of resultsets into one. 如何将几个结果集合并为一个。 Say I have these five sql selects, which all take the same 'simple' input (10):
假设我有这五个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
How do I UNION or JOIN or sub-query, so that I get a row with all the columns; 我如何UNION或JOIN或子查询,以便我得到所有列的行; agentid, latitude, longitude, availability, updated, email, name, phone, company, pt1num, pt2num, pt3num?
agentid,纬度,经度,可用性,更新,电子邮件,名称,电话,公司,pt1num,pt2num,pt3num?
One way is to use Common table expressions and then cross join them 一种方法是使用通用表表达式 ,然后交叉连接它们
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
Another way is to use inline views 另一种方法是使用内联视图
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
These are only really reasonable if you know each select is only going to return one row 仅当您知道每个选择仅返回一行时,这些才是真正合理的
You could also use local variables to do each select 您还可以使用局部变量进行每次选择
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
and then select them out 然后选择它们
SELECT @agentid agentid, @latitude latitude, ... @pt1num...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.