1

我有 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

请帮忙,因为我不知道再去哪里看:)。

4

1 回答 1

0

要在数据透视表中获取数据,in 子句应该从表中获取正确的数据

你可以从这个查询中得到更多的想法

如果 1 和 2 不在您的表中,它将不会显示为计数和列值

CREATE TABLE #OrderHeader
(ORDERNR INT,
ORDERCONTACT CHAR(5))

CREATE TABLE #ORDERDETAIL
(ORDERNR INT,
ORDERSERIAL VARCHAR(10)
)

INSERT INTO #OrderHeader VALUES ( 1, 'X')
INSERT INTO #ORDERDETAIL VALUES ( 1, 'X1')
INSERT INTO #ORDERDETAIL VALUES ( 1, 'X2')
INSERT INTO #ORDERDETAIL VALUES ( 1, 1)
INSERT INTO #ORDERDETAIL VALUES ( 1, 2)


SELECT * FROM #OrderHeader
SELECT * FROM #ORDERDETAIL

SELECT  OrderNr,
        OderContact,
        [1] as OrderSerial1,
        [2] as OrderSerial2,
        [3] as OrderSerial3
FROM
    (select H.OrderNR as OrderNr,
            OrderContact as OderContact,
            ORDERSERIAL
    from #OrderHeader H inner join #ORDERDETAIL D on H.OrderNr = D.OrderNr
    ) AS PivSource
PIVOT
(count(ORDERSERIAL) for ORDERSERIAL in([1],[2],[3])) as pvt


DROP TABLE #OrderHeader
DROP TABLE #ORDERDETAIL
于 2013-07-22T08:52:07.293 回答