0

我想知道怎么做!!!。

现在:我有卖家按组划分,提供宠物

宠物位于名为PetTable(PETCode 和 PETName)的表中

CREATE TABLE PetTable ( 
PETCode VARCHAR(16) UNIQUE NOT NULL, 
PETName VARCHAR(32) NOT NULL 
);
INSERT INTO PetTable (PETCode, PETName) VALUES 
('Pet1','Black Cat'), 
('Pet2','Big Dog'), 
('Pet3','Gold Fish'), 
('Pet4','Parlot'), 
('Pet5','Bird'), 
('Pet6','Small Dog'); 

卖家存储在SellerTable(CodeSeller 和 NameSeller)中

CREATE TABLE SellerTable  ( 
CodeSeller VARCHAR(16) UNIQUE NOT NULL, 
NameSeller VARCHAR(32) NOT NULL 
); 
INSERT INTO SellerTable  (CodeSeller, NameSeller) VALUES 
('Seller0','John '), 
('Seller1','Paul '), 
('Seller2','David '),   
('Seller3','James ');

卖家使用具有 3 个字段( PETCode 、CodeSeller、Quantity)的 SalesTable与宠物相关联

CREATE TABLE SalesTable ( 
PETCode VARCHAR(16) NOT NULL, 
CodeSeller VARCHAR(16) NOT NULL, 
Quantity INT NOT NULL 
);
INSERT INTO SalesTable (PETCode, CodeSeller, Quantity) VALUES 
('Pet1', 'Seller0', '9'), 
('Pet2', 'Seller0', '81'), 
('Pet3', 'Seller0', '7'), 
('Pet4', 'Seller1', '63'), 
('Pet5', 'Seller1', '4'), 
('Pet6', 'Seller1', '50'), 
('Pet2', 'Seller2', '61'), 
('Pet5', 'Seller2', '72'), 
('Pet4', 'Seller3', '83'), 
('Pet2', 'Seller3', '94'), 
('Pet1', 'Seller3', '8'); 

我的查询很简单,如何知道每个 PET 的销售额!PET1,PET2,PET3的所有销售额的总和是多少......继续......

感谢您的宝贵帮助...

4

2 回答 2

0

您需要加入PetTablewith SalesTable, with PetTable.PetCode = SalesTable.PetCode,并且由于它们共同的列具有相同的名称,您可以使用 a NATURAL JOIN

SELECT PETName, SUM(Quantity)
FROM PetTable NATURAL JOIN SalesTable
GROUP BY PETName

在此处查看小提琴。

或者,如果您只需要 SUM by PETCode,并且您对宠物名称不感兴趣,则可以在不连接的情况下使用它:

SELECT PETCode, SUM(Quantity)
FROM SalesTable
GROUP BY PETCode
于 2013-04-17T15:57:09.133 回答
0

您需要先加入表格。由于您对 不感兴趣,因此使用表SellerName连接表就可以满足您的需求。PetTableSalesTableLEFT JOIN

在我的查询中使用LEFT JOINover的原因是它仍然会包含尚未售出的内容。INNER JOINPets

SELECT  a.PETCode,
        a.PETName,
        SUM(b.Quantity) TotalSold
FROM    PetTable a
        LEFT JOIN SalesTable b
            ON a.PETCode = b.PETCode
GROUP   BY  a.PETCode, a.PETName

要进一步了解有关联接的更多信息,请访问以下链接:

输出

╔═════════╦═══════════╦═══════════╗
║ PETCODE ║  PETNAME  ║ TOTALSOLD ║
╠═════════╬═══════════╬═══════════╣
║ Pet1    ║ Black Cat ║        17 ║
║ Pet2    ║ Big Dog   ║       236 ║
║ Pet3    ║ Gold Fish ║         7 ║
║ Pet4    ║ Parlot    ║       146 ║
║ Pet5    ║ Bird      ║        76 ║
║ Pet6    ║ Small Dog ║        50 ║
╚═════════╩═══════════╩═══════════╝
于 2013-04-17T15:57:51.167 回答