选择正确的查询

时间:2015-04-02 14:21:26

标签: sql sql-server tsql subquery

我必须构建一个查询,为客户创建一个表格 - ' Frank Spencer'(您将在下面的客户表格中看到他)。

新表应该保留客户购买的每件商品的总数,而不包括那些尚未发货的订单,每个产品只出现在新表中一次。

我的表格如下。

enter image description here

enter image description here

你能告诉我下面哪一个最好吗?

a)with customer as (select * from customers where lower(CustomerName) = 'frank spencer'),customerorders as(select OrderId from orders o where o.CustomerId in(select CustomerId from customer) and OrderShipped = 'True') select sum(oi.QuantityOrdered) as TotalOrdered, s.ItemName into franksorders from orderitems oi join stock s on oi.StockItemId = s.StockItemId where OrderId in(select * from customerorders) group by ItemName order by ItemName

b)with customer as (select * from customers where lower(CustomerName) = 'frank spencer') join customerorders as(select OrderId from orders o where o.CustomerId in(select CustomerId from customer) and OrderShipped = 'True') select total(oi.QuantityOrdered) as TotalOrdered, s.ItemName into new table franksorders using orderitems oi join stock s on oi.StockItemId = s.StockItemId where OrderId in(select * from customerorders) group by ItemName order by ItemName

c)with customer (select * from customers where 'frank spencer' in (CustomerName)) with customerorders (select OrderId from orders o where o.CustomerId in(select CustomerId from customer) and OrderShipped = 'True') select sum(oi.QuantityOrdered) as TotalOrdered, s.ItemName create table franksorders using orderitems oi join stock s on oi.StockItemId = s.StockItemId where OrderId in(select * from customerorders) group by ItemName order by ItemName

d)using customer with (select * from customers where CustomerName = 'frank spencer' and customerorders with(select OrderId from orders o where o.CustomerId in(select CustomerId from customer) then OrderShipped = 'True') select sum(oi.QuantityOrdered) as TotalOrdered, s.ItemName into franksorders from orderitems oi join stock s on oi.StockItemId = s.StockItemId where OrderId in(select * from customerorders) group by ItemName order by ItemName

1 个答案:

答案 0 :(得分:0)

B,C和D中有一个USING,我不知道SQL Server是否支持它。使用是,但不是使用。所以答案是A.下一次,您可以使用poorsql.com来格式化您的代码,这样就更容易找到错误。

WITH customer
AS (
    SELECT *
    FROM customers
    WHERE lower(CustomerName) = 'frank spencer'
    )
    ,customerorders
AS (
    SELECT OrderId
    FROM orders o
    WHERE o.CustomerId IN (
            SELECT CustomerId
            FROM customer
            )
        AND OrderShipped = 'True'
    )
SELECT sum(oi.QuantityOrdered) AS TotalOrdered
    ,s.ItemName
INTO franksorders
FROM orderitems oi
INNER JOIN stock s ON oi.StockItemId = s.StockItemId
WHERE OrderId IN (
        SELECT *
        FROM customerorders
        )
GROUP BY ItemName
ORDER BY ItemName