我有这三个表:
表1:
InvoiceId InvoiceNumber CompanyId
-------------------------------------------------
3 1 2
4 2 2
6 1 1
7 3 2
8 4 2
9 2 1
表2:
CompanyId CompanyName
-------------------------------
1 Name1
2 Name2
表3:
InvoiceId AcceptDate AcceptType
---------------------------------------------
3 AAAA O
3 BBBB P
6 CCCC P
4 DDDD O
7 EEEE O
9 FFFF P
7 GGGG P
表1和表3具有一对多的关系,表3具有多个链接的行。表3每个InvoiceId最多有2行。
任务
我想将表3行分组以得到这个结果:
InvoiceId AcceptDate1 AcceptDate2
--------------------------------------------
3 AAAA BBBB
6 CCCC null
4 DDDD null
and ....
然后将这些结果与表1和表2结合起来给出:
InvoiceId InvoiceNumber AcceptDate1 AcceptDate2 Name
--------------------------------------------------------------------------
3 1 AAAA BBBB Name2
4 2 DDDD null Name2
7 3 EEEE GGGG Name2
8 4 null null Name2
6 1 CCCC null Name1
9 2 FFFF null Name1
AcceptDate1和AcceptDate2是静态的。
答案 0 :(得分:0)
你想要的是Pivot the data。
BEGIN TRAN
create table #table1 (InvoiceId int, InvoiceNumber int, CompanyId int)
create table #table2 (CompanyId int, CompanyName varchar(50))
create table #table3 (InvoiceId int, AcceptDate datetime, AcceptType char(1))
insert into #table1 values (3, 1, 2)
insert into #table1 values (4, 2, 2)
insert into #table1 values (6, 1, 1)
insert into #table1 values (7, 3, 2)
insert into #table1 values (8, 4, 2)
insert into #table1 values (9, 2, 1)
insert into #table2 values (1, 'Name1')
insert into #table2 values (2, 'Name2')
insert into #table3 values (3, '2012-01-01', 'o')
insert into #table3 values (3, '2012-01-02', 'p')
insert into #table3 values (6, '2012-01-03', 'p')
insert into #table3 values (4, '2012-01-04', 'o')
insert into #table3 values (7, '2012-01-05', 'o')
insert into #table3 values (9, '2012-01-06', 'p')
insert into #table3 values (7, '2012-01-07', 'p')
SELECT #table1.InvoiceId, #table1.InvoiceNumber, t.o as [AcceptDate1], t.p as [AcceptDate2], #table2.CompanyName
FROM #table3 pivot (max(AcceptDate) for AcceptType IN ("o", "p")) as t
JOIN #table1 on #table1.InvoiceId = t.InvoiceId
JOIN #table2 on #table2.CompanyId = #table1.CompanyId
ROLLBACK
这给出了:
InvoiceId InvoiceNumber AcceptDate1 AcceptDate2 CompanyName
----------- ------------- ----------------------- ----------------------- --------------------------------------------------
3 1 2012-01-01 00:00:00.000 2012-01-02 00:00:00.000 Name2
4 2 2012-01-04 00:00:00.000 NULL Name2
6 1 NULL 2012-01-03 00:00:00.000 Name1
7 3 2012-01-05 00:00:00.000 2012-01-07 00:00:00.000 Name2
9 2 NULL 2012-01-06 00:00:00.000 Name1
(5 row(s) affected)