我有 2 张桌子:
- 带有 OrderNr 和 OrderContact 列的“OrderHeader”。
- '带有 OrderNr 和 OrderSerial 列的 OrderDetail。
对于每个 ordernr,最多有 3 个 ordererials。所以,我想要得到的是一个带有列的表:
- 订单号
- 奥德联系
- 订单序列号1
- 订单序列号2
- 订单序列号3
我现在被我的支点困住了
SELECT OrderNr,
OderContact,
[1] as OrderSerial1,
[2] as OrderSerial2,
[3] as OrderSerial3
FROM
(select H.OrderNR as OrderNr,
OrderContact as OderContact,
OrderSerialsNr
from OrderHeader H inner join OrderDetail D on H.OrderNr = D.OrderNr
) AS PivSource
PIVOT
(count(OrderSerialsNr) for OrderSerialsNr in([1],[2],[3])) as pvt
我为此使用了 Adventureworks DB。
USE [AdventureWorks2008R2]
GO
create view [test].[OrderHeader] (OrderNr,OrderContact)
as
SELECT SalesOrderID,
FirstName + ' ' + LastName
FROM Sales.SalesOrderHeader INNER JOIN
Sales.Customer ON Sales.SalesOrderHeader.CustomerID = Sales.Customer.CustomerID INNER JOIN
Person.Person ON Sales.Customer.PersonID = Person.Person.BusinessEntityID
GO
CREATE view [test].[OrderDetail] (OrderNr,OrderSerialsNr,Price)
as
SELECT [SalesOrderID]
,[ProductID]
,[unitPrice]
FROM [AdventureWorks2008R2].[Sales].[SalesOrderDetail]
where SalesOrderID in (select SalesOrderID
from [AdventureWorks2008R2].[Sales].[SalesOrderDetail]
group by SalesOrderID
having COUNT(SalesOrderID) < 4)
GO
请帮忙,因为我不知道再去哪里看:)。