简体   繁体   中英

GROUP BY and SUMS in MS ACCESS

I'm trying to get a report of how many article have been sold, especially which one was sold more, both in terms of numbers and price.

I'm trying the above query, thinking that using the [PRICE]*[total] in the group by expression, it could worked. unluckily it does not. I've try also to put the alias in the group by expression, but nothing more, it only says that I need to use a grouping expression for the column: [PRICE]*[total] which is what I thought I have done.

SELECT TOP 20 ARTIC, Sum(TOTGIA) AS total, [PRICE]*[total] AS a
FROM Car
GROUP BY ARTIC, [PRICE]*[total]
ORDER BY Sum(TOTGIA) DESC;

anyone could lead me in the good direction?

the error is:

"You tried to execute a query that does not include the specified expression '[PRICE]*[total]' as part of an aggregate function."

the table is something like this:

|artic|totgia|price
+++++++++++++++++++
|aaa  |  1   | 10
|aaa  |  4   | 10
|bbb  |  1   | 200

I would like to have:

|aaa| 5 | 50
|bbb| 1 | 200

so aaa is the first one for number of sells, but bbb is first for cash

The problem here is that you are trying to use the total alias in the select and in the group by. You do not have access to the alias at this time. Instead, you will either need to refer to the actual column values in place of total. In other cases, you can create a subselect and use the alias, but this does not apply to your query as it is written.

SELECT TOP 20 ARTIC, Sum(TOTGIA) AS total, PRICE*Sum(TOTGIA) AS a
FROM Car
GROUP BY ARTIC, PRICE
ORDER BY Sum(TOTGIA) DESC;

If you have an article listed with several different prices, this query will return several rows. So, this data:

 |artic|totgia|price +++++++++++++++++++ |aaa | 1 | 10 |aaa | 4 | 20 |bbb | 1 | 200 

Would return these results:

 |aaa| 1 | 10 |aaa| 4 | 80 |bbb| 1 | 200 

This would happen because we have specifically told sql that we want the unique articles and prices as their own rows. However, this is probably a good thing because in the above scenario, you wouldn't want to return that aaa has a quantity of 5 with a value of 50, since the total value is 90. If this is a possible scenario for your data, you would make this query into a subselect and group all the data for the unique articles together.

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