2

Here's the scenario: I've got an orders table and a customers table. I'd like to calculate the SUM of the column total for specific storeID. The problem is that my company used to store the storeID in the customers table but now it's being stored in the orders table. There are orders in our database where the storeID is only set in the customers table, only set in the orders table, or set in both tables.

Here's some schema example data for reference:

Table Orders:

+----+-------+------------+---------+
| id | total | customerID | storeID |
+----+-------+------------+---------+
|  0 |   100 |          1 | 1       |
|  1 |    50 |          1 | NULL    |
|  2 |    75 |          1 | 1       |
+----+-------+------------+---------+

Table Customers:

+----+----------+
| id | storeID  |
+----+----------+
|  1 | 1 | NULL |
+----+----------+

The query I've been playing around with trying to calculate the sum of the order total looks like this:

SELECT SUM(total)
FROM orders o
INNER JOIN customers c
        ON c.ID = o.customerID
WHERE ISNULL(c.storeID,o.storeID) = @storeID

This query works, but it's super slow because we have so many order records in our database. Is there a more efficient way to do this? I'm using SQL Server 2008 R2.

Thanks, Matt

4

1 に答える 1

1
SELECT SUM(total)
FROM orders o
WHERE coalesce(o.storeID, (
                    select storeID
                    from customers
                    where id = o.customerID
                ) = @storeID

ところで、注文テーブルを更新するだけで、そこからのみクエリを実行できます。

update orders o
set storeID = (
        select storeID
        from customers
        where id = o.customerID
        )
where storeID is null
于 2012-10-11T16:12:19.747 に答える