I have this table:
tbl_Sales
----------------------------------------
|Item_Code|Sold|Date |
|---------+----+-----------------------|
|BBPen100 |30 |2017-04-17 00:00:00.000|
|BBPen100 |21 |2017-04-13 00:00:00.000|
|BBPen100 |13 |2017-04-12 00:00:00.000|
|XSHIRT80 |0 |2017-04-17 00:00:00.000|
|XSHIRT80 |24 |2017-04-14 00:00:00.000|
|XSHIRT80 |9 |2017-04-13 00:00:00.000|
|XSHIRT80 |5 |2017-04-12 00:00:00.000|
|YBSHADE7 |0 |2017-04-17 00:00:00.000|
|YBSHADE7 |6 |2017-04-15 00:00:00.000|
|YBSHADE7 |0 |2017-04-13 00:00:00.000|
|YBSHADE7 |11 |2017-04-12 00:00:00.000|
----------------------------------------
How can I get the last non-zero Sold value from the last 2 working days? This means that I need to exclude the Weekends and Holidays. I have this table which consists holidays.
tbl_Holiday
-------------------------
|Holiday_Date |
|-----------------------|
|2017-04-14 00:00:00.000|
|2017-05-01 00:00:00.000|
|2017-10-18 00:00:00.000|
|2017-12-25 00:00:00.000|
-------------------------
So for example today is 2017-04-18, the output should be like this:
---------------------
|Item_Code|Last_Sold|
|---------+---------|
|BBPen100 |30 |
|XSHIRT80 |9 |
|YBSHADE7 |0 |
---------------------
The goal is to get the last Sold value from LAST 2 working days, so the counting start on 2017-04-17. Output analysis:
BBPen100-since it has value from last 1 working day (2017-04-17), that value will be retrieved.
XSHIRT80-Zero value from last 1 working day (2017-04-17)
-2017-04-16 & 2017-04-15 are weekends
-2017-04-14 is holiday
-So value from 2017-04-13 will be retrieved.
YBSHADE7-Zero value from last 1 working day (2017-04-17)
-2017-04-16 & 2017-04-15 are weekends
-2017-04-14 is holiday
-2017-04-13 has Zero value
-2017-04-12 is beyond Last 2 working days
-So value retrived should be Zero
Currently, I have this query:
SELECT Item_Code, Sold AS 'Last_Sold'
FROM tbl_Sales
WHERE CONVERT(date, [DATE]) = CASE
WHEN CONVERT(date, [DATE]) = CONVERT(date, DATEADD(day, -1, GETDATE())) THEN CONVERT(date, DATEADD(day, -1, GETDATE()))
WHEN CONVERT(date, [DATE]) <> CONVERT(date, DATEADD(day, -1, GETDATE())) THEN CONVERT(date, DATEADD(day, -2, GETDATE()))
But of course, this would not meet the requirements.
Please help me resolve this.
IMPORTANT NOTE: Consider the holidays on weekends and what if I run the program on weekends or holidays.
Thank you in advance.
You could try it
Sample data
You could calculate @2PreviousWorkingDays before @CurrentDate
And your desired result:
Demo link: Rextester