Share via

Please solve this question

Midhun Jose 21 Reputation points
2021-04-07T06:03:47.827+00:00

There is a Customer table that has a list of customers and Gift Voucher table that has list of gift vouchers. No of vouchers is less than No of customers. Customer table has one column Customer_Id. Voucher has one column Voucher_id.

Customer_Id
Abhinash
Vipin
Mahesh
Bijoy
Bhabani
Ashutosh

Voucher_Id
ABXFH
SDFGH
ERTYY
PPLKM

Develop a SQL query that will assign one voucher to one customer until all vouchers are exhausted and populate the table as shown.
Customer_Key Gift Voucher Key
Abhinash ABXFH
Vipin SDFGH
Mahesh ERTYY
Bijoy PPLKM
Bhabani -
Ashutosh -

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

EchoLiu-MSFT 14,626 Reputation points
2021-04-07T06:42:12.557+00:00

Please try:

CREATE TABLE Customer (Customer_Id varchar(255));  
INSERT INTO Customer VALUES('Customer_Id'),('Abhinash'),('Vipin'),('Mahesh'),('Bijoy'),('Bhabani'),('Ashutosh')  
  
CREATE TABLE Voucher (Voucher_Id varchar(255) UNIQUE);  
INSERT INTO Voucher VALUES('ABXFH'),('SDFGH'),('ERTYY'),('PPLKM')  
  
;with cte   
as(select *,row_number() over(order by Customer_Id) rr from Customer)  
,cte2 as(select *,row_number() over(order by Voucher_Id) rr from Voucher)  
  
select Customer_Id Customer_Key,Voucher_Id Gift_Voucher_Key  
from cte c1  
join cte2 c2 on c1.rr=c2.rr  

If you have any question, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.

Best Regards
Echo


If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.