我有以下两个表,您也可以在sql fiddle
here中找到这些表:
CREATE TABLE Sales (
Sales_Date DATE,
Product TEXT,
Sales_Channel TEXT,
Sales_Quantity VARCHAR(255)
);
INSERT INTO Sales
(Sales_Date, Product, Sales_Channel, Sales_Quantity)
VALUES
("2017-05-23", "Product A", "Online", "400"),
("2018-09-10", "Product A", "Store", "200"),
("2018-12-14", "Product B", "Store", "600"),
("2019-01-03", "Product B", "Store", "700"),
("2019-02-15", "Product B", "Online", "650"),
("2019-03-20", "Product A", "Online", "380"),
("2019-08-25", "Product C", "TradeFair", "120"),
("2019-09-16", "Product C", "Online", "470"),
("2019-09-16", "Product A", "Store", "920"),
("2019-10-20", "Product B", "TraidFair", "860"),
("2020-01-03", "Product B", "TradeFair", "610");
CREATE TABLE Purchasing (
Purchasing_Date VARCHAR(255),
Product TEXT,
Purchasing_Channel TEXT,
Purchasing_Quantity VARCHAR(255)
);
INSERT INTO Purchasing
(Purchasing_Date, Product, Purchasing_Channel, Purchasing_Quantity)
VALUES
("2017-01-10", "Product A", "Local_Supplier", "1000"),
("2017-01-16", "Product A", "Local_Supplier", "3000"),
("2017-01-19", "Product B", "Reseller", "1500"),
("2018-05-14", "Product B", "Reseller", "4500"),
("2018-05-14", "Product C", "Foreign_Import", "1800"),
("2019-04-16", "Product C", "Foreign_Import", "2300");
注意::每种产品都明确分配给一个购买渠道!
现在,我要查询一个结果如下:
Sales_Date Product Channel Sales_Quantity
2017-05-23 Product A Online_Local_Supplier 400
2018-09-10 Product A Store_Local_Supplier 200
2018-12-14 Product B Store_Reseller 600
2019-01-03 Product B Store_Reseller 650
: : : :
: : : :
: : : :
如您所见,我想将Sales_Channel
和Purchasing_Channel
合并到一栏中。
因此,我设置了以下查询:
SELECT
s.Sales_Date,
s.Product,
(Case sales_channel
When "Online" Then "Online"
When "Store" then "Store"
When "TradeFair" then "Traidfair"
ELSE "NoSalesChannel"
END) AS Channel,
s.Sales_Quantity
FROM Sales s
JOIN Purchasing p ON p.Product = s.Product
GROUP BY 1,2;
此查询正确插入了Sales_Channel
,但是我该如何更改它,以便将Purchasing_Channel
添加到期望的结果中呢?
答案 0 :(得分:0)
尝试distinct
:
SELECT distinct
s.Sales_Date,
s.Product,
concat(s.Sales_Channel, '_', p.Purchasing_Channel) as Chanel,
s.Sales_Quantity
FROM Sales s
JOIN Purchasing p ON p.Product = s.Product
尝试concat
和group by
。
SELECT
s.Sales_Date,
s.Product,
concat(s.Sales_Channel, '_', p.Purchasing_Channel) as Chanel,
s.Sales_Quantity
FROM Sales s
JOIN Purchasing p ON p.Product = s.Product
group by s.Sales_Date,
s.Product,
concat(s.Sales_Channel, '_', p.Purchasing_Channel),
s.Sales_Quantity
这将为您提供结果:
Sales_Date | Product | Chanel | Sales_Quantity
2017-05-23 Product A Online_Local_Supplier 400
2018-09-10 Product A Store_Local_Supplier 200
2018-12-14 Product B Store_Reseller 600
2019-01-03 Product B Store_Reseller 700
2019-02-15 Product B Online_Reseller 650
2019-03-20 Product A Online_Local_Supplier 380
2019-08-25 Product C TradeFair_Foreign_Import 120
2019-09-16 Product C Online_Foreign_Import 470
2019-09-16 Product A Store_Local_Supplier 920
2019-10-20 Product B TraidFair_Reseller 860
P.S。请检查jarlh给您的所有评论。