【问题标题】:SQL Sum & Count with Multiple Conditions and Tables具有多个条件和表的 SQL Sum & Count
【发布时间】:2017-08-11 04:59:06
【问题描述】:

我有 3 个表如下:

Cust_table columns: C_ID, C_Country
Store_table columns: S_ID, S_Name, S_Country
Tran_table columns: C_ID, S_ID, S_Type, Spending

客户表

C_ID   C_Country
999    CN
888    TW

Store_table

S_ID   S_Name   S_Country
123    ABC      CN
456    DEF      JP
789    GHI      CN

转表

C_ID   S_ID   S_Type   Spending
999    123    ML       106
888    123    ML       642
888    456    Outlet   364
888    789    ML       422
999    456    ML       263

问题: 找出每家商店的本地和非本地客户数量及其各自的消费,按 S_country 和 S_Type 排序。 (S_Country=C_Country 定义本地和非本地客户和支出)

ANS 必填字段:S_Country、S_ID、S_Name、No_Local、Local_Spending、No_NonLocal、NonLocal_Speding

预期结果

S_Country S_ID  S_Name  No_Local Local_Speding No_NonLocal NonLocal_Spending
CN        123   ABC     1        106           1           642
CN        789   GHI     0        0             1           422
JP        456   DEF     0        0             2           627

我最初的想法是使用 count/countif(?) 来找出本地和非本地支出的数量,总支出的总和。 但我不知道如何在一个查询中包含所有条件。 有人可以帮忙吗?谢谢。

到目前为止,我有

SELECT DISTINCT store_table.S_Country, 
store_table.store_ID,
Store_table.store_name,
SUM (spending)

FROM store_table, tran_table

WHERE Store_table.store_ID=tran_table.store_ID;

【问题讨论】:

  • 请添加表结构虚拟值和预期结果
  • 到目前为止您尝试过什么?如果您先自己尝试并在此处发布代码(如果代码不起作用)并发布示例数据和所需的输出,那就太好了。
  • s_type 是否有国家名称或者 s_country name /c_country 取决于它是本地/非本地客户吗?
  • 如果您可以发布这些表格的一些数据以及您期望看到的所需结果,那就太好了......否则我们可能会对此做出不同的解释
  • 对不起,我已经添加了表格和预期结果。 S_country 和 C_country 是对应的

标签: mysql sql sqlite


【解决方案1】:

商店可能没有匹配的交易,因此您必须使用外连接。

使用CASE expressions 删除不需要的(非)本地值:

SELECT S_Country,
       S_ID,
       SUM(CASE WHEN S_Country =  C_Country THEN 1        END) AS No_Local,
       SUM(CASE WHEN S_Country =  C_Country THEN Spending END) AS Local_Spending,
       SUM(CASE WHEN S_Country <> C_Country THEN 1        END) AS No_NonLocal,
       SUM(CASE WHEN S_Country <> C_Country THEN Spending END) AS NonLocal_Spending
FROM Store_table
LEFT JOIN Tran_table USING (S_ID)
LEFT JOIN Cust_table USING (C_ID)
GROUP BY S_ID;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多