简体   繁体   中英

COUNT() with GROUP BY - Query to get number of times a set of values appear in a column SQL

Just struggling with this question.

Write a query that selects the following details about the sides that have been ordered in orders:

• The side ID number and side name.

• How many orders the side has been ordered in (regardless of quantity).

I have created a view already and this is the table for it (ordered_sides_details is the name of the view)

View Table

I've wrttien this query but I believe it just counts the number of rows instead of how many times each side is ordered.

SELECT ordered_sides_details.side_name, COUNT(*) 
FROM ordered_sides_details 
GROUP BY ordered_sides_details.side_name;

This is the resulting table

Obviously its incorrect as 1.25L Coke has only been in 1 order.

Any help with solving this would be awesome. Thanks.

Solution

There must be something wrong with view you've created.

This should be enough to yield proper results:

SELECT
     side_id
    ,side_name
    ,COUNT(*) AS total_count
FROM dbo.orders
GROUP BY side_id, side_name

Boostrapping (SQL Server)

Scripts for bootstrapping your example:

IF NOT EXISTS (SELECT 1 FROM sys.tables t WHERE t.object_id = OBJECT_ID('dbo.orders'))
BEGIN
    CREATE TABLE orders
    (
        order_id INT,
        side_id INT NOT NULL,
        side_name NVARCHAR(100) NOT NULL,
        ordered_quantity INT NOT NULL,
        total_cost MONEY NOT NULL
    );
END;

INSERT INTO orders (order_id, side_id, side_name, ordered_quantity, total_cost)
VALUES 
(10, 1, '390ml Coke', 1, 3.00),
(5, 2, '1.25l Coke', 2, 10.00),
(8, 3, 'Lava Cake', 3, 8.85),
(7, 4, 'Chicken Wings', 4, 14.00),
(6, 5, 'Garlic Bread', 4, 7.80),
(5, 6, 'Healthy Kale Chips', 3, 16.50),
(5, 6, 'Healthy Kale Chips', 2, 11.00),
(4, 5, 'Garlic Bread', 1, 1.95),
(3, 4, 'Chicken Wings', 1, 3.50),
(2, 3, 'Lava Cake', 2, 5.90);

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