如何在Sql Server中编写嵌套查询/子查询 [英] How Do I Write A Nested Query/Subquery In Sql Server

查看:165
本文介绍了如何在Sql Server中编写嵌套查询/子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了某种目的,我必须获取当前日期生日所在客户端的一些数据(例如Email,ClientName,DOB,CNIC,ClientId),然后将其记录/插入新表Birthday_Client。但由于数据库结构,我很难进行查询,因为它是这样的:



DB-1有表帐户和客户

账户表有电子邮件,CNIC和ClientID

&

客户表有ClientName



DB- 2有表Client_Detail

Client_Detail有DOB(即出生日期)




所以我必须只获取数据那些生日是当前日期的客户,然后将这些选定的数据插入到新表中,即生日_客户。

请帮忙!



PS :为了方便您使用ClientID列存在于所有表中。

I have to fetch some data (e.g. Email, ClientName, DOB, CNIC, ClientId) of the clients who's birthday lies on current date for some purpose, and then log/insert it into a new table "Birthday_Client". But i am getting difficulty in making query because of DB structure it is like this:

DB-1 has tables Account and Client
Account table has Email, CNIC and ClientID
&
Client table has ClientName

DB-2 has table Client_Detail
Client_Detail has DOB(i.e. date of birth)


so i have to fetch the data of only those clients who's birthday is on current date and then insert this selected data into a new table viz Birthday_Client.
Please help!

P.S. : For making things easy for you ClientID column is present in all the tables.

推荐答案

听起来您需要在两个客户端表之间进行连接然后将信息插入第三个表格。



您可以使用类似

插入到Birthday_Client(fieldname 1,fieldname2等)中选择fieldname 1 ,db-1内部连接数据库中的dbname 1,dbname 2 = db-2.ClientID,db-2.DOB = getdate()





您可能需要注意dob字段。如果它包含时间,那么您可能需要扩展查询,使其在当天的开始和结束之间。
Sounds like you need a join between the two client tables and then insert the information into a third table.

You can use something like
insert into Birthday_Client (fieldname 1, fieldname2 etc) select fieldname 1, fieldname2 etc from db-1 inner join db-2 on db-1.ClientID = db-2.ClientID where db-2.DOB = getdate()


You may need to be careful about the dob field. If it includes time then you may need to expand the query so that it is between the start and end of the day.


You can use something like

insert into Clients_Birthday
(clientId) select db-1.ClientIDfrom db-1 inner join db-2 on db-1.ClientID = db-2.ClientID
 where  DATEPART(d, db-2.DOB= DATEPART(d, GETDATE())
    AND DATEPART(m, db-2.DOB= DATEPART(m, GETDATE())


这篇关于如何在Sql Server中编写嵌套查询/子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆