I have to write some sales data to a table for each district. each product is totaled and now I need to get the min sale for all products. <<
Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. We need to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL.
Did you know that there is ISO week notation? Build a calendar table with this data and use it.
Do you know what a repeated group violation of 1NF is? What you posted is not normalized, so you will be kludging DML all the time.
I have to write some sales data to a table for each district. each product is totaled and now I need to get the min sale for all products. <<
Total of what? The dollars or the quantity? Since we have no DDL, no spec and no sample data, I will guess quantity.
CREATE TABLE Sales
(sales_week CHAR(10) NOT NULL-able
CHECK(sales_week LIKE '[12][0-9][0-9][0-9]W[0-5][0-9]'),
product_gtin CHAR(15) NOT NULL,
county_code CHAR(5) NOT NULL
CHECK (county_code LIKE '[A-Z][A-Z][0-9][0-9][0-9]'),
district_code CHAR(3) NOT NULL CHECK (district_code LIKE ??),
PRIMARY KEY (sales_week, product_gtin, county_code, district_code)
sale_qty INTEGER NOT NULL CHECK (sale_qty > 0)
));
The problem is it should only select if it is greater than zero. I have a couple minimum values that are less than or equal to zero so with the code below they are NULL. I want it to select the minimum value that is greater than zero. <<
How is that possible? What attribute of a product are we adding that can be negative? Not price, not quantity? This why we want DDL, sample data and specs in a normalized table.
WITH X1
AS
(SELECT sale_week, county_code, district_code,
SUM(sale_qty) AS sale_qty_tot
FROM Sales
GROUP BY sale_week, county_code, district_code),
X2
AS
(SELECT sale_week, county_code, district_code, sale_qty_tot,
DENSE_RANK()
OVER (PARTITION BY sale_week, county_code, district_code,
ORDER BY sale_qty_tot DESC) AS sale_qty_tot_rank
FROM X1)
SELECT *
FROM X2
WHERE sale_qty_tot_rank IN (1,2);
Untested due to lack of specs and sample data.