SQL Server:根据table1中的值返回特定table2列中的值

时间:2016-07-11 04:27:30

标签: sql-server

我有一个从2个表中获取数据的查询。

  • Transaction表包含week_id,customer_id,upc12,sales_dollars
  • Products表包含upc12,column_1,column_2,column_3

我希望我的查询根据事务表中customer_id的内容返回products表中的值。 customer_id = 1应返回column_1customer_id = 2应返回column_3等。

SELECT
    t.week_id, 
    customer_id, 
    upc12, 
    p.___________ sum(t.sales_dollars)
FROM 
    transaction t, products p
WHERE 
    t.upc_12 = p.upc_12
GROUP BY 
    t.week_id, customer_id, upc12, p.___________

对不起,如果这没有意义,但我的研究不是很好,因为我不知道如何正确地提出我的问题。你可能猜到我是SQL的新手。

谢谢!

1 个答案:

答案 0 :(得分:0)

这是一种方法:

;WITH cte as
(
SELECT
    t.week_id, 
    customer_id, 
    upc12, 
    CASE customer_id
        WHEN 1 THEN p.Column_1
        WHEN 2 THEN p.Column_2
        WHEN 3 THEN p.Column_3
    END As ColByCustomer,
    t.sales_dollars
FROM transaction t
INNER JOIN products p on t.upc_12 = p.upc_12
)

SELECT week_id, customer_id, upc12, ColByCustomer, SUM(sales_dollars)
FROM cte
GROUP BY week_id, customer_id, upc12, ColByCustomer