2
Answers

How to minimized output rows in a query in my Windows Form Application

Photo of David Godistei

David Godistei

Jun 24
449
1

Greetings to all.

I am on-building a Windows Form Application where a stored procedure (build on two tables - Stock and Sales) is built on the database server (.mdf). Then, on the client side a form is built to pull data from the stored procedure on the server side.

The following is the SQL language used to build the stored procedure namely, AvailableQty:-

CREATE PROCEDURE [dbo].[AvailableQty]

       @code int = 0

AS

       SELECT Stock.Category, Stock.ProductName, Stock.Model, Stock.StockQty, Sales.SaleQty FROM Stock, Sales

       WHERE Stock.Code = Sales.Code AND Stock.Code = @code

       RETURN 0
SQL

A form was built on the client side. Data were entered in both the stock and sales tables (two entries made in the stock table and three in the sales table) respectively. The AvailableQty form is to pull data per product, from both tables and display the result.

The results displayed were more than expected. I wish to attach here and image as example. There are duplicates of rows that give wrong totals.

Please I will appreciate a solution for my problem.

Thanks

Answers (2)

1
Photo of Jithu Thomas
194 10.2k 112.8k Jun 24

To resolve the issue of duplicate rows and incorrect totals in your results, you need to make sure that the join between the Stock and Sales tables is correct and that you are aggregating the data appropriately. Here’s a revised version of your stored procedure that uses a proper join and aggregates the sales quantities:

 

please update the SQL Procedure as below: -

 

CREATE PROCEDURE [dbo].[AvailableQty]
    @code int = 0
AS
BEGIN
    -- Aggregate sales quantities
    SELECT 
        s.Category, 
        s.ProductName, 
        s.Model, 
        s.StockQty, 
        ISNULL(SUM(sa.SaleQty), 0) AS SaleQty
    FROM 
        Stock s
    LEFT JOIN 
        Sales sa ON s.Code = sa.Code
    WHERE 
        s.Code = @code
    GROUP BY 
        s.Category, s.ProductName, s.Model, s.StockQty
END
Accepted
1
Photo of Riddhi Valecha
435 3.3k 431.2k Jun 24

Could you share the table structure and few records so it may help in making query.