One SQL interview question
I failed to apply for a job last year. I was taken to a seemingly simple question, but I did not find a good big case.
Do you have any good solutions?
Title:
There are two tables, T1, T2,
Table T1:
Seller | non_seller
----------
A B
A c
A D
B
B c
B d
C
C B
C d
D
D B
D C
Table t2:
Seller | coupon | bal
-----------------------
A 9 100
B 9 200
C 9 300
D 9 400
A 9.5 100
B 9.5 20
A 10 80
The following results must be listed using the SELECT statement: ------ for example, sum (BAL) of A is the sum of B, C, D, and sum (BAL) of B is a, c, and of d .......
Do not increase the burden on the database, such as using temporary tables.
NON-SELLER | coupon | sum (BAL)
---------------
A 9 900
B 9 800
C 9 700
D 9 600
A 9.5 20
B 9.5 100
C 9.5 120
D 9.5 120
A 10 0
B 10 80
C 10 80
D 10 80
Question: the goal is to count non_seller information. I don't know why the question is answered.
Create an environment/****** object: Table [DBO]. [T2] script Date: 03/15/2011 09:37:19 ******/set ansi_nulls ongoset quoted_identifier ongocreate table [DBO]. [T2] ([seller] [nvarchar] (50) null, [Coupon] [float] Null, [Bal] [int] Null) on [primary] goinsert [DBO]. [T2] ([seller], [Coupon], [Bal]) values (n' A', 9,100) insert [DBO]. [T2] ([seller], [Coupon], [Bal]) values (n' B ', 9,200) insert [DBO]. [T2] ([seller], [Coupon], [Bal]) values (n'c', 9,300) insert [DBO]. [T2] ([seller], [Coupon], [Bal]) values (n'd', 9,400) insert [DBO]. [T2] ([seller], [Coupon], [Bal]) values (n'a', 9.5, 100) insert [DBO]. [T2] ([seller], [Coupon], [Bal]) values (n' B ', 9.5, 20) insert [DBO]. [T2] ([seller], [Coupon], [Bal]) values (n'a', 10, 80)/***** object: table [DBO]. [T1] script Date: 03/15/2011 09:37:19 ******/set ansi_nulls ongoset quoted_identifier ongocreate table [DBO]. [T1] ([seller] [nvarchar] (50) null, [non_seller] [nvarchar] (50) null) on [primary] goinsert [DBO]. [T1] ([seller], [non_seller]) values (n'a', n' B ') insert [DBO]. [T1] ([seller], [non_seller]) values (n'a', n'c') insert [DBO]. [T1] ([seller], [non_seller]) values (n'a', n'd') insert [DBO]. [T1] ([seller], [non_seller]) values (n' B ', n'a') insert [DBO]. [T1] ([seller], [non_seller]) values (n' B ', n'c') insert [DBO]. [T1] ([seller], [non_seller]) values (n' B ', n'd') insert [DBO]. [T1] ([seller], [non_seller]) values (N 'C', N 'A') insert [DBO]. [T1] ([seller], [non_seller]) values (N 'C', N 'B') insert [DBO]. [T1] ([seller], [non_seller]) values (N 'C', N 'D') insert [DBO]. [T1] ([seller], [non_seller]) values (n'd', n'a') insert [DBO]. [T1] ([seller], [non_seller]) values (n'd', n' B ') insert [DBO]. [T1] ([seller], [non_seller]) values (n'd', n'c ')
Select non_seller, coupon, sum ([sum (BAL)]) as [sum (BAL)] From (select * from (select t1.non _ seller, t2.coupon as coupon, sum (BAL) as [sum (BAL)] from T1 join T2 on t1.seller = t2.seller group by non_seller, coupon) xunionselect seller, coupon, 0 from T2) ygroup by non_seller, coupon