Calculate my product stock. (SQL) - sql

So I have a product for example cake (It's a soft for a cofeteria). I know that my cake expires after 48h.
Today, for example I have 10 cakes in my stock, and I want to know if some of my cakes are expired, to send it back to deposit, and eliminate it from my stock.
I have my product table which contains product and expiration date in hours (Example: 48 h)
I have another table where I calculate my stock now. (And a procedure who does that).

You might required to add new columns in Production tracking table and Sale table, that might be either BatchNumber or ProductionDate, then get list of cake produced and its batch number subtract with list of cake sold for each BatchNumber based on production time display it as expired or tasty.
SELECT
Product.ProductName,
Production.BatchNumber,
SUM(Production.Qty) - SUM(Sale.Qty) AS Stock
CASE WHEN DATEADD(hh, Product.ExpireInHrs, Production.ProductionTime) >= CURRENT_TIMESTAMP THEN 'Expired' ELSE 'Tasty' END
FROM Product
INNER JOIN Production ON Production.ProductId = Product.ProductId
INNER JOIN Sale ON Sale.ProductId = Product.ProductId AND Production.BatchNumber = Sale.BatchNumber
GROUP BY
Product.ProductName,
Production.BatchNumber
For the query above I presume that you have three tables Product, Production and Sale with BatchNumber columns in Production and Sale table, ProductionTime column in Production table.

Related

SQL - how to show SKUs with the lowest price from a query

I am making a query for a price comparison site and I have to provide them a csv file with certain data. I have done the query and the first problem was that the prices that showed up in it were the full prices from sql database. So when we have for example a discount applied to the whole category of products the price shown is still the full price not the discounted one. I solved that by checking if an SKU is in a discounted category and the query calculates the price accordingly.
The new problem is now that a query checks through categories and if one sku is in multiple categories it creates a row with same SKU for each category and I end up with multiple rows with same SKU and only one has correct price (discounted one).
Example query result. NOTE that the Price column is a calculated result not the data from the table.
SKU
Product
Price
A
Ball
19
A
Ball
19
A
Ball
15
B
Cube
10
B
Cube
8
How do I filter it to just this
SKU
Product
Price
A
Ball
15
B
Cube
8
You need GROUP BY with aggregate function MIN()
SELECT SKU
, Product
, MIN(Price) as Price
FROM <table>
GROUP
BY SKU
, Product

SQL dynamic WHERE clause for every row

I need your expertise and guidance to understand the approach I should use to solve the task below. I have skimmed through existing answers but have not found good matches (unless they were there but they required extensive SQL knowledge and experience)
TASK
calculate total sales forecast per product for a period of time (from beginning of sales until end of end sales).
DATA
Table_1: Product - Calendar Week - Sales Forecast
Table_2: Product - Sales Start (Date_1, Individual for every product)
Table_3: Product - Sales End (Date_2, Individual for every product )
SOLUTION
My initial thought was to use simple WHERE BETWEEN clause but SQL crashes every time I execute the
SELECT
Product,
SUM(Sales_Forecast)
FROM Table_1 as T1
LEFT JOIN Table_2 as T2
ON T1.Product=T2.Product.
LEFT JOIN Table_3 as T3
ON T1.Product=T3.Product
WHERE T1.Calender_week BETWEEN T2.Sales_Start AND T3.Sales_End
GROUP BY Product
Thus the time period I am looking for is not static and it varies depending on a product and its start and end date of sales.
How should I better approach this task?
Thanks in advance,
f

Redshift - Joining two tables based on date ranges

I have a table that stores date when product was bought and another table that states what offers were run during different time frames.
I am trying to join both these tables based on dates to find out if there was any sale during the date when purchase was made.
Given below is how much looks like:
Sale data:
prod_id,sale_date
1001,2019-02-02
1002,2019-05-04
1003,2019-03-04
1004,2019-04-21
Table that stores offers run by date is as below:
offer_name, start_date, end_date
offer_1,2019-01-02,2019-03-01
offer_2,2019-02-02,2019-03-06
offer_3,2019-04-01,2019-05-01
offer_4,2019-06-01,2019-07-01
I am trying to link the Sale data with the date when sale run data to get the below output:
prod_id,sale_date,offer_name
1001,2019-02-02,offer_1
1002,2019-05-04,
1003,2019-03-04,offer_2
1004,2019-04-21,offer_3
Its quite simple. You can simply use between to get the offer_name.
SELECT S.PROD_ID,S.SALE_DATE,O.OFFER_NAME
FROM Sale_data S
JOIN offers_run_data O
ON S.SALE_DATE BETWEEN O.START_DATE AND O.END_DATE

Merging two SQL tables

I have a table called Store Sales with the following columns
Date
Total Qty Sold
RRP
Total Value Sold
Branch No.
Barcodes
Unit Cost
Then I have another table called ESales that contains this
Inv Date
Our Ship Qty
Unit Price (RRP Inc VAT)
Line Total
Invoice
Order
Line
Brand
Part
Description
Our Order Qty
Unit Price (Exc VAT)
Discount %
Discount Amt (Inc VAT)
Discount Amount (Exc VAT)
Tax Category
Tax Exempt
Group
Sales Cat
Cust. ID
Title
Customer
Name
Tax ID
Rep. ID
Credit Memo
Unit Price
Amount
Category ID
Cust. Amount
Number01
ShortChar01
ShortChar02
Clubcard
There are matching fields but none with the same name. They are
Inv Date = Date
Our Ship Qty = Total Qty Sold
Unit Price (RRP Inc VAT) = RRP
Line Total = Total Value Sold
What I want to do in merge the values in StoreSales to ESales and create additional columns for the data that is not there, these are
Branch No
Barcodes
Unit Cost
Any ideas how to insert the matching values and create the three new ones?
Instead of creating a new table, I would just start with a query that shows you all the data you are describing. The way you merge data from multiple tables together is by using a JOIN command. Here is a example query that shows everything from the ESales table and the additional columns from the StoreSales table you described:
SELECT e.*, s.[Branch No], s.[Barcodes], s.[Unit Cost]
FROM StoreSales s
INNER JOIN ESales e ON
e.[Inv Date] = s.[Date] AND
e.[Our Ship Qty] = s.[Total Qty Sold] AND
e.[Unit Price (RRP Inc VAT)] = s.[RRP] AND
e.[Line Total] = s.[Total Value Sold]
Once you get a query you like, you can save it as a VIEW which essentially lets you interact with the result of this query as if it were a separate table.
I will caution you that you have to be very careful doing this. Usually, data will have some kind of common field like a Order ID or a product SKU that makes it very clear what unique item you are referencing in the database. Joining by things like date, order total, price, etc is bad practice. This is because there is no way to guarantee that there aren't two orders with the same date or the same order total. Those things are not unique to any one particular order.

SQL Count, counting Halfs!

I have a rather strange problem:
when certain sales are made (completed) a record is inserted with the event and ID of the sales person, currently this table is queried and the 'Count' is used (along with usual date boundaries) to calculate number of 'closed' sales. This is currently working fine.
The problem now is some sales are 'shared' sales, products are linked via leads, usually the lead and the product are always by the same sales person, however in some rare cases lead can be created by on salesperson and the product 'sold' by another in such case the 'sales' calculation needs to award 0.5 (half) a point to each sales person.
What would be the best SQL approach to solve this?
(SQL Server 2005)
SELECT
SUM(CASE WHEN SaleUserID = LeadUserID THEN 1 ELSE 0.5)
FROM
sales
WHERE
(SaleUserID = #targetID OR LeadUSerID = #targetID)
-- AND dateCriteria
Just use SUM() instead of COUNT(), i.e.
SELECT SUM(CASE WHEN shared=1 THEN 0.5 ELSE 1 END) FROM sales WHERE ...
I guess you have some way to distinguish between a "full sale" and a "half sale".
Count separately the number of "full sales" and the number of "half sales".
Then add full + 0.5*half.