SQL子查询中的条件

时间:2013-10-29 11:09:45

标签: sql subquery

我做了这个查询,现在我必须找到不同的方法来返回相同的结果。

SELECT CompanyName, COUNT(Orders.OrderID) Orders
FROM Customers LEFT OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Country LIKE 'Germany' OR Country LIKE 'Brazil' 
GROUP BY CompanyName HAVING COUNT(Orders.OrderID) >= 10
ORDER BY Orders ASC;

所以我做了这个,但我不知道我应该在哪里放“> = 10”条件。有人能告诉我怎么做吗?我尝试了一些方法,但它没有用。

SELECT CompanyName, (SELECT COUNT(OrderID) FROM Orders WHERE Customers.CustomerID = Orders.CustomerID) AS Orders
FROM Customers
WHERE Country LIKE 'Germany' OR Country LIKE 'Brazil'
ORDER BY Orders ASC;

适用于MS SQL Server ...

2 个答案:

答案 0 :(得分:0)

SELECT
      COMPANYNAME,
      ( SELECT
            COUNT ( ORDERID )
       FROM
            ORDERS
       WHERE
            CUSTOMERS.CUSTOMERID = ORDERS.CUSTOMERID
       HAVING
            COUNT ( ORDERID ) >= 10 )
          AS ORDERS
FROM
      CUSTOMERS
WHERE
      COUNTRY LIKE 'Germany'
      OR COUNTRY LIKE 'Brazil'
ORDER BY
      ORDERS ASC;

答案 1 :(得分:0)

   SELECT CompanyName, COUNT(Orders.OrderID) Orders
   FROM Customers JOIN Orders ON Customers.CustomerID = Orders.CustomerID
   WHERE Country IN('Germany','Brazil') 
   GROUP BY CompanyName 
   HAVING COUNT(Orders.OrderID) >= 10
   ORDER BY Orders ASC;