我有一个从2个表中获取数据的查询。
Transaction
表包含week_id,customer_id,upc12,sales_dollars Products
表包含upc12,column_1,column_2,column_3 我希望我的查询根据事务表中customer_id
的内容返回products表中的值。 customer_id = 1
应返回column_1
,customer_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的新手。
谢谢!
答案 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