简体   繁体   中英

Basic SQL Sums, Selects, WHERES, GROUP BY statements

I'm currently working on this data.

What should be resulting:

在此处输入图片说明

What should be produced is the result at the bottom of that picture.

Instead, I'm getting the result:

在此处输入图片说明

My code is the following:

SELECT distinct(username) as 'Name', p.price as 'Price', p.quantity as 'Quantity', (p.price * p.quantity) as 'Total'
 FROM users u, purchase p
WHERE u.userID = p.userID 
ORDER BY (username) asc  ; 

I am wondering how would I go about adding up the unique usernames (Alice's 4 and 1.5 to produce 5.5) and how do I also get Matt's name to display on the data?

Just minor changes, but the important thing is to group by user and not order by user

SELECT username as 'Name', SUM(p.price * p.quantity) as 'Total'
 FROM users u, purchase p
WHERE u.userID = p.userID 
GROUP BY username; 

从[用户]中选择u.name,总和(数量*价格)u左加入u.name对u.id = p.userId组购买p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM