在SQLITE中使用SUM函数

时间:2014-10-03 12:47:03

标签: sql database sqlite

我有这个基本的sqlite3数据库。在我的商店表中,我专注于numberOfItems类别。例如,在我的PurchaseToStore表中,4个不同的商店购买玉米饼,其数量(numberOfItems)为5,55,55,55。我想要做的是计算这些值的总和。所以(55 + 55 + 55 + 5)= 170。

CREATE TABLE Store(

storeName VARCHAR(30),
storeid INTEGER,
PRIMARY KEY(storeid)

);

CREATE TABLE item(

itemName VARCHAR(30) ,
itemId INTEGER,
PRIMARY KEY(itemId)

);


CREATE TABLE PurchasedToStore(

storeid INTEGER,
itemId INTEGER,
numberOfItems INTEGER,
expirationMonth Integer,
PRIMARY KEY(storeid, itemID),
FOREIGN KEY(storeid) REFERENCES STORE(storeid),
FOREIGN KEY(itemid) REFERENCES item(itemid)

);


INSERT INTO Store Store('Meijer', 1);
INSERT INTO Store VALUES('Kroger', 2);
INSERT INTO Store VALUES('Walmart', 3);
INSERT INTO Store VALUES('Kmart', 4);


INSERT INTO item VALUES('taco', 556);
INSERT INTO item VALUES('burrito', 557);
INSERT INTO item VALUES('cheese', 600);

INSERT INTO STORE VALUES(1, 556, 5, 12);
INSERT INTO STORE VALUES(2, 556, 55, 11);
INSERT INTO STORE VALUES(3, 556, 55, 10);
INSERT INTO STORE VALUES(4, 556, 55, 2);

以下是我必须尝试做的事情:

SELECT sum(numberOfItems)
FROM item join purchasetostore
WHERE storeid = itemid;

1 个答案:

答案 0 :(得分:2)

目前还不清楚最终目标是什么,但稍微改变你的位置条件会得到你想要的总和。你想要匹配两个表中的itemid;

SELECT sum(numberOfItems)
FROM item join PurchasedToStore
WHERE item.itemid = PurchasedToStore.itemid;

可能稍微有用的查询可能包括项目的项目名称和每个名称的总和;

SELECT item.itemname, sum(numberOfItems)
FROM item join PurchasedToStore
WHERE item.itemid = PurchasedToStore.itemid
GROUP BY item.itemname;

A simple SQLfiddle with both queries