导航
  • 主页
  • 基础类
  • 应用实例
  • 新技术前沿

sql查询

wishY 2008-01-15 12:12:04
我有两个 甚至多个sql语句 如果查出的结果类似这样,怎么把他们合并到一个里面去,难道一定要先插到临时表?
month age1
------ -----------
03 69
04 50
没有行受影响。
(返回 1 行)
month age2
------ -----------
03 480
04 100
没有行受影响。

希望结果
month age1 age2
-------------------
03 69 480
04 50 100
难道只能用临时表吗?这样一来不是慢死啊,有没有什么好办法?
...全文
84 点赞 收藏 8
写回复
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
威尔亨特 2008-01-16
left join ..... on ...
回复
JL99000 2008-01-16
select a.month,a.age1,b.age2 from (这里放你得到第一表的查询语句 ) as a left join (这个放你得到第二表的查询语句) b
on a.month=b.month
正确
接分
回复
wishY 2008-01-15
那我不是要写死啊,贴个sql语句,用来统计年龄段的。

declare @sql1 nvarchar(1000)
set @sql1 = 'SELECT [month] ,sum([count]) as age1 FROM (SELECT Convert(nvarchar(2),d.CheckTime,101) as [month] ,COUNT(DATEDIFF(yy, P.Birthday, GETDATE()))as [count]
FROM Deals as D INNER JOIN Houses as H ON D.HouseID = H.HouseID inner join Peoples P on D.BuyID = P.PeopleID '
set @sql1 = @sql1 + ' where Convert(nvarchar(4),d.CheckTime,102) = '''+@year+''' '
if @cishu = '1'
begin
if @term <> ''
set @sql1 = @sql1 + ' and h.XiangMu like ''%'+@term+'%'' '
end
else
begin
if @term <> ''
set @sql1 = @sql1 + ' and (h.XiangMu like ''%'+@term+'%'' or replace((h.lu + h.Nong + ''弄''),'' '','''') like ''%'+@term+'%'' )'
end

set @sql1 = @sql1 + ' group by DATEDIFF(yy, P.Birthday, GETDATE()),Convert(nvarchar(2),d.CheckTime,101) having DATEDIFF(yy, P.Birthday, GETDATE()) < 18) AS 临时表 group by [month]'
if @month <> ''
set @sql1 = @sql1 + ' having [month] = '''+@month+''' '
if @season <> ''
begin
if @season = '1'
set @sql1 = @sql1 + ' having [month] between 1 and 3 '
if @season = '2'
set @sql1 = @sql1 + ' having [month] between 4 and 6 '
if @season = '3'
set @sql1 = @sql1 + ' having [month] between 7 and 9 '
if @season = '4'
set @sql1 = @sql1 + ' having [month] between 10 and 12 '
end

exec sp_executesql @sql1

有没有办法用一个写出来啊,我现在想 只能换 条件 DATEDIFF(yy, P.Birthday, GETDATE()) < 18 查出不同年龄段的了。
回复
dobear_0922 2008-01-15
表名都搞得一样,呵呵
来握个手,,,
回复
dobear_0922 2008-01-15
select a.month,age1,age2 
from (select month,age1 from ...) a
join (select month,age2 from ...) b on a.month=b.month


回复
-狙击手- 2008-01-15
select a.month,b.age1,b.age2
from (select month ,......) a
left join (select month ,......) b on.a.month = b.month
回复
dobear_0922 2008-01-15
可以试试联合查询
回复
sp4 2008-01-15
回复
发动态
发帖子
MS-SQL Server
创建于2007-09-28

3.2w+

社区成员

MS-SQL Server相关内容讨论专区
申请成为版主
社区公告
暂无公告