I am trying to use the distinct clause to add these two values together, but when I do it still gives me two separate rows. Ultimately I want to add these two rows together.
A screenshot of the table view from my query
Basically this is a database that keeps track of books, pages, quantity, price, etc. I'm trying to find the total value of books that fit a certain genre (nonfiction), and are over a certain price threshold. I then multiply these two together to get the value.
There's two records in my database that fit this description, and it is displaying the individual values for both of these records
SELECT DISTINCT Sum([Price]*[Quantity]) AS Total_Value
FROM Merchandise INNER JOIN Book ON Merchandise.MerchID = Book.ISBN
GROUP BY Book.Genre, Merchandise.Price, Merchandise.Quantity
HAVING (((Book.Genre)="Nonfiction") AND ((Merchandise.Price)>18));
Note: I submitted this answer based on the MS Access tags. However, I think it should work the same in SQL Server, but no idea about MySQL.
GROUP BY Book.Genre, Merchandise.Price, Merchandise.Quantity
asks for a separate row for each unique combination of those 3 fields. Since you want only one row, remove Merchandise.Price
and Merchandise.Quantity
from the GROUP BY
clause.
Also DISTINCT
is not useful in a GROUP BY
query, so you can remove that, too.
SELECT Sum([Price]*[Quantity]) AS Total_Value
FROM Merchandise INNER JOIN Book ON Merchandise.MerchID = Book.ISBN
GROUP BY Book.Genre
HAVING Book.Genre='Nonfiction' AND Merchandise.Price>18;
If you change the HAVING
to a WHERE
clause, you can exclude the rows you don't want evaluated before doing the GROUP BY
aggregation:
SELECT Sum([Price]*[Quantity]) AS Total_Value
FROM Merchandise INNER JOIN Book ON Merchandise.MerchID = Book.ISBN
WHERE Book.Genre='Nonfiction' AND Merchandise.Price>18
GROUP BY Book.Genre;
Actually, for this particular query, I suspect you don't need GROUP BY
at all:
SELECT Sum([Price]*[Quantity]) AS Total_Value
FROM Merchandise INNER JOIN Book ON Merchandise.MerchID = Book.ISBN
WHERE Book.Genre='Nonfiction' AND Merchandise.Price>18;
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.