创建一个mySQL视图,根据标志对另一个表中的特定列求和?

时间:2014-07-29 20:54:20

标签: mysql

SQLFiddle链接:http://sqlfiddle.com/#!2/8c29c/1

我有一个表用于客户信息,例如ID,名字,姓氏等。然后,我有一个第二个表,其中包含已放置的订单。有两种类型的订单,常规订单和自定义订单。然后,每种订单的总数都有一列。

这就是客户端表的样子

[Clients table]
ID - auto incrementing integer
fname - firstname
lname - lastname

这就是订单表的样子

[Orders table]
orderID - auto incrementing integer
client_ID - fk to Client table
complete - 1 if order is completed, 0 if order is not completed
custom_order - 1 if a custom order, 0 if not a custom order
total - total balance for non custom orders
custom_total - total balance for custom orders

我尝试创建一个包含clientID列的视图,并将所有已完成的自定义订单和常规订单余额的总和汇总在一起。

因此,例如,如果ID为599的客户在Order表中有2个已完成的订单,custom_total为$ 25.05的自定义订单,以及总计$ 5的常规订单,那么在视图中它应显示clientID为599,订单总数为2,总订单余额为30.05美元。

以下是我目前为视图声明所做的事情。当然它不起作用。

CREATE OR REPLACE VIEW client_order_totals AS
SELECT
    c.ID,
    c.fname,
    c.lname,
    CASE
        WHEN o.custom_order = 1 AND o.complete = 1
            THEN o.custom_total
        WHEN o.custom_order = 0 AND o.complete = 1
            THEN o.total
        ELSE 0
    END AS totals,
    SUM(totals) AS realtotal, --This line doesn't work.
    COUNT(*) AS ordercount --This doesn't work either.
FROM Clients c
LEFT JOIN Orders o ON c.ID = o.client_ID
GROUP BY c.ID

以下是应该发生的事情的完整示例

[Clients table]
ID  fname   lname
29, George, Smith
30, Jerree, Leris

[Orders table]
orderID client_ID  complete  custom_order  total  custom_total
      1,       29,        1,            1,     0,           10
      2,       29,        1,            0,     3,            0
      3,       29,        0,            0,     6,           30
      4,       30,        0,            1,     7,            5

因此,新的client_order_totals视图应如下所示

[client_order_totals view]
ID  fname   lname  ordercount  ordertotal
29  George  Smith           2          13
30  Jerree  Leris           0           0

谢谢!

2 个答案:

答案 0 :(得分:0)

SELECT c.*
     , SUM(o.complete=1)
     , SUM(CASE WHEN o.complete=1 THEN total + custom_total ELSE 0 END) ttl
  FROM clients c
  JOIN orders o
    ON o.client_id = c.id
 GROUP
    BY c.id;

http://sqlfiddle.com/#!2/d0bbf/4

或类似的东西

答案 1 :(得分:0)

看起来不需要if语句:

CREATE OR REPLACE VIEW client_order_totals AS
select a.ID, a.fname, a.lname, sum(a.complete) ordercount, sum(a.complete*(a.total+a.custom_total)) ordertotal
from Clients a
join Orders b on a.ID = b.client_ID
group by a.ID;