连接两个表并使用sum公式的逻辑

时间:2014-07-26 01:28:50

标签: sql

需要一些SQL连接逻辑的帮助

表1

  • CustomerID(ex.1234123)
  • Customer_name(ex.string)

表2   - CustomerID(ex.1234但在列中有多次)   - 产品(同一列内不同行上的狗粮,猫粮等)   - 产品收入

当一个表有多行数据聚合成一行ID和一行数据时,如何将两个表连接在一起。

行 CustomerID ---- Customer_name -------狗粮(收入)------猫粮(收入)

希望这是有道理的,谷歌搜索这个废话并没有真正找到我想要的东西。

3 个答案:

答案 0 :(得分:0)

尝试:

select   c.customerid,
         C.Customer_name,
         sum(case when product = 'dog food' then revenue else 0 end) as dog_food_rev,
         sum(case when product = 'cat food' then revenue else 0 end) as cat_food_rev
from     table1 c
    join table2 p
      on c.customerid = p.customerid
group by c.customerid, c.Customer_name

这假设收入字段名为REVENUE

还假设产品价值为“狗粮”。和猫粮#39;完全(必要时重命名)

SQL Fiddle

答案 1 :(得分:0)

转动表格

Select CustomerID, Customer_name, IsNull([Dog Food],0) [Dog Food], IsNull([Cat Food],0) [Cat Food]
from (
  select A.*, B.product, B.Revenue
  from Table1 A
  inner join Table2 B
     on A.CustomerID = B.CustomerID
) A
 pivot (sum(revenue) for product in ([Dog Food],[Cat Food])) B

SQL Fiddle

答案 2 :(得分:0)

使用连接和条件聚合执行此操作:

select t1.customerid,
       t1.Customer_Name,
       sum(case when product = 'dog food' then revenue else 0 end) as DogFood,
       sum(case when product = 'cat food' then revenue else 0 end) as CatFood
from table1 t1 join
     table2 t2
     on t1.customerid = t2.customerid
group by t1.customerid, t1.Customer_Name

SQL Fiddle