为条件的列选择多于1的语句

时间:2014-01-14 23:17:10

标签: sql

我有Order表(OrderID,salemanID,ProductTypeID,month,year ...),Saleman表(salemanID,...)和ProductTypes表(ProductID,Product_type ....)。

我试图让查询选择所有订单号,订单号超过1个产品类型和销售员。

这是我的问题:

Select O.OrderID, S.SalemanName, P.Product_type, count(P.productID)
From Order O join Saleman s ON O.salemanID = s.salemanID
             join ProductTypes P ON O.ProductTypeID = P.ProductID
Where O.month= '01'
and   O.year='2014'
Group by O.OrderID, S.SalemanName, P.Product_type
Having count(P.productID)>1

输出是这样的:

+------------+-------+------------+
|Order Number|Saleman|Product Type|
+------------+-------+------------+
|1234        |Andrew |Tables      |
+------------+-------+------------+
|1234        |Scott  |Tables      |
+------------+-------+------------+
|4321        |Andrew |Chairs      |
+------------+-------+------------+
|4321        |John   |Chairs      |
+------------+-------+------------+

我想要的是一个包含多种产品类型的订单

+------------+-------+------------+
|Order Number|Saleman|Product Type|
+------------+-------+------------+
|1234        |Andrews|Tables      |
+------------+-------+------------+
|1234        |Barton |Chair       |
+------------+-------+------------+
|4321        |Andrews|Beds        |
+------------+-------+------------+
|4321        |John   |Chairs      |
+------------+-------+------------+
|4321        |John   |Desks       |
+------------+-------+------------+

请帮助,非常感谢

1 个答案:

答案 0 :(得分:0)

希望这有助于你。

SELECT  O.OrderID [Order Number], S.SalemanName [Saleman], P.Product_type [Product Type] --, Count(P.productID)
FROM    (
            SELECT  x.OrderID
            FROM    [Order] x
                    Inner Join ProductTypes PT On x.ProductTypeID = PT.ProductID
            WHERE   x.month= '01'
                    And x.year='2014'
            GROUP BY x.OrderID
            HAVING Count(PT.ProductID) > 1
        ) O
        Left Outer Join [Order] OD on O.OrderID = OD.OrderID
        Left Outer Join Saleman S On OD.salemanID = S.salemanID
        Left Outer Join ProductTypes P On OD.ProductTypeID = P.ProductID