I want to find the number of days from my SQL table before my instock level goes negative. Is there a way to do that on SQL? I can find the number of days that have negative instock levels but I am not able to figure out a way to stop the counter for days when instock goes negative.
create TEMPORARY VIEW instock_ssd_fc as
( select
ilbo.asin,
ilbo.snapshot_day,
sum(coalesce(ilbo.on_hand_quantity, 0) - coalesce(greatest(ilbo.allocated_quantity, ilbo.bound_quantity), 0)) as inventory_units_ssd_fc,
sum(coalesce(ilbo.in_transit_quantity, 0)) as in_transit_quantity_ssd_fc,
sum(coalesce(ilbo.unallocated_customer_demand,0)) as unallocated_customer_demand_ssd_fc,
sum(case when iog.inventory_owner_group_id is not null then coalesce(ilbo.on_hand_quantity, 0) - coalesce(greatest(ilbo.allocated_quantity, ilbo.bound_quantity), 0) else 0 end) as inventory_units_retail_ssd_fc
from d_unified_inv_level_by_owner as ilbo
inner join asin_selected as a
on a.asin = ilbo.asin
left join iog
on ilbo.inventory_owner_group_id = iog.inventory_owner_group_id
and ilbo.region_id = ${region_id}
where ilbo.region_id = ${region_id}
and upper(ilbo.inventory_condition_code) = 'SELLABLE'
and ilbo.snapshot_day between cast('${date}' as timestamp) - interval 1 weeks and cast('${date}' as timestamp)
and ilbo.warehouse_id = '${fc}'
group by ilbo.asin, ilbo.snapshot_day
);
From the above query, I want to check how many days the ASIN had a positive inventory. For example, if I start looking for instock levels from 12/27 and go behind, if on snapshot_day of 12/06 the inventory level goes to negative for the first time starting from 12/27, my number of days will be 21.
Assuming your table has a column date for the date and instock for the quantity, you could use try:
SELECT COUNT(*)
FROM yourTable
WHERE date < (SELECT date FROM yourTable
WHERE instock < 0
ORDER BY date LIMIT 1);
Related
SELECT zones.name AS "Zone Name",
( CASE WHEN (date_format(bookings.booking_date, '%a') = 'Fri')
THEN (COUNT(bookings.id) /9) ELSE (COUNT(bookings.id) /10)
END
)AS `Number of Bikers on the Period`
FROM bookings
LEFT JOIN zones
ON bookings.zone_id = zones.id
WHERE {{created_at}}
GROUP BY zones.name
ORDER BY `Number of Bikers on the period` DESC
I am trying to retrieve a bar chart
X-Axis: Zones Name
Y-Axis: Case
The case is as the following:
if it is Friday then divide count booking ID by 9
if it is not Friday divide count booking ID by 10
The code is working but not delivering the right numbers.
Note: each booking could be in Fridays or Weekdays
I have a sales table with price column as decimal(8, 2) and I'm running the query below to get the total price
select sum(case when status = 1 then price * quantity when status = 2 then price * quantity * -1 else 0 end) as total from sales;
It's working perfectly but my results are usually intergers so I end up with trailing zeros all the time. It'd be nice to just return the whole number if there is no decimal part
like akina said in his comment ...
you can cast the sum result to UNSIGNED INTEGER
select
CAST(sum(case when status = 1 then price * quantity when status = 2 then price * quantity * -1 else 0 end) AS UNSIGNED)
as total from sales;
I have a forecast algorithm
WITH CTE_AllIDs AS
(
SELECT TOP 22 ID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM sys.columns
)
SELECT
c.ID
,OrderMonth = CASE WHEN r.ID IS NOT NULL
THEN r.OrderMonth
-- elaborate function to get the short month name and year
ELSE ordermonth + 1
END
,OrderQuantity
,Trend
,Forecast = CASE WHEN Trend IS NOT NULL AND c.ID <> (SELECT MAX(ID) FROM #Temp_Regression)
THEN NULL
-- For the last actual value (September in this example), we want forecast to have the same
-- value as the trendline (instead of NULL). This prevents a gap in the line charts in SSRS.
WHEN Trend IS NOT NULL AND c.ID = (SELECT MAX(ID) FROM #Temp_Regression)
THEN Trend
-- If trend is not found, it means we can calculate a forecast.
-- However, we also need to check if the month for which we calculate the forecast comes after
-- the actual values. Suppose we don't have values for January, then we don't want to calculate
-- a forecast for January as well. Only for the last 3 months of the year in this example.
WHEN Trend IS NULL AND c.ID > (SELECT MAX(ID) FROM #Temp_Regression)
THEN (#slope * (c.ID % 100)) + #intercept
ELSE NULL
END
FROM CTE_AllIDs c
LEFT JOIN #Temp_Regression r ON c.ID = r.ID;
The results
How can I do this in the values of the OrderMoth columns increase by one the? 2023, 2024, etc.
Thanks.
Your Else in your Case Statement will always contain Null. Try this.
ELSE (Select Max(OrderMonth) From #Temp_Regression) + ((C.ID) - (Select Max(ID) From #Temp_Regression))
Looking for MaxDate, its most recent date and the interval between. Of the MaxDate and most recent, I also need the quantities for each so I can also find the interval
Table "tblITEM_InventoryCount" structure is as follows:
Item_No Count Date Qty
001 08/29/2015 12
001 08/15/2015 17
001 07/15/2015 19
Item No 001
Max(CountDate) 08/29/2015
PriorCountDate 08/15/2015
Interval Days (MaxDate-RecentDate) 14
MaxDate Quantity 12
PriorCountDate Quantity 17
Interval Qty (17-12) 5
Currently using a query to find last two count dates for each ITEM_NO
SELECT tblITEM_InventoryCount.ITEM_NO, tblITEM_InventoryCount.Quantity, tblITEM_InventoryCount.CountDate
FROM tblITEM_InventoryCount
WHERE (((tblITEM_InventoryCount.CountDate)>=NthInGroup([tblITEM_InventoryCount].[ITEM_NO],2)))
ORDER BY tblITEM_InventoryCount.ITEM_NO, tblITEM_InventoryCount.CountDate DESC;
Then I am using a second query to calculate my data:
SELECT qryLAST2_InventoryCount_TRANSACTIONS.ITEM_NO, qryLAST2_InventoryCount_TRANSACTIONS.CountDate, (SELECT MAX([CountDate]) FROM [qryLAST2_InventoryCount_TRANSACTIONS] AS [Old Orders] WHERE [Old Orders].[CountDate] < [qryLAST2_InventoryCount_TRANSACTIONS].[CountDate] AND [Old Orders].[ITEM_NO] = [qryLAST2_InventoryCount_TRANSACTIONS].[ITEM_NO]) AS PriorCountDate, [CountDate]-[PriorCountDate] AS DaysInterval, qryLAST2_InventoryCount_TRANSACTIONS.Quantity, (SELECT Last([Quantity]) FROM [qryLAST2_InventoryCount_TRANSACTIONS] AS [OldCount] WHERE [OldCount].[Quantity] < [qryLAST2_InventoryCount_TRANSACTIONS].[Quantity] AND [OldCount].[ITEM_NO] = [qryLAST2_InventoryCount_TRANSACTIONS].[ITEM_NO]) AS PriorQuantity, [Quantity]-[PriorQuantity] AS QuantityInterval, [QuantityInterval]*30/[DaysInterval] AS [Usage]
FROM qryLAST2_InventoryCount_TRANSACTIONS
GROUP BY qryLAST2_InventoryCount_TRANSACTIONS.ITEM_NO, qryLAST2_InventoryCount_TRANSACTIONS.CountDate, qryLAST2_InventoryCount_TRANSACTIONS.Quantity
ORDER BY qryLAST2_InventoryCount_TRANSACTIONS.ITEM_NO, qryLAST2_InventoryCount_TRANSACTIONS.CountDate DESC;
I am not getting the results I need. The query returns two record lines for each item along with their max or last countdate, the previous countdate, intervaldays, qty, last qty, and interval.
I need max or last countdate and its qty count and prior countdate and its qty count.
Any help would be greatly appreciated.
Try this :
select
tab.item_no,
tab.Max_Date,
tab.PriorCountDate,
DateDiff ("d", tab.Max_Date, tab.PriorCountDate) as IntervalDays,
tab.MaxDateQty,
tab.PriorCountDateQty,
( tab.MaxDateQty-tab.PriorCountDateQty) as IntervalQty,
from
( select
temp1.item_no as item_no,
temp1.m as Max_Date,
(select MAX(count_date) from tblITEM_InventoryCount where count_date <> temp1.m ) as PriorCountDate,
temp1.q as MaxDateQty,
(select MAX(Qty) from tblITEM_InventoryCount where Qty <> temp1.q) as PriorCountDateQty,
from
( select item_no as i, Qty as q, MAX(count_date) as m
group by item_no, Qty ) as temp1
inner join
tblITEM_InventoryCount as temp2
on
temp1.item_no = temp2.item_no
)
as tab ;
I have a table with records and a period of time for each record, like reservations for instance. So my records look like this:
Table-reservations
id room datefrom dateto
1 'one' '2015-09-07' '2015-09-12'
2 'two' '2015-08-11' '2015-09-02'
3 'three' '2015-06-11' '2015-06-14'
4 'two' '2015-07-30' '2015-08-10'
5 'four' '2015-06-01' '2015-06-23'
6 'one' '2015-03-21' '2015-03-25'
...
n 'nth' '2015-06-01' '2015-07-03'
Also there is a table with rooms containing an ID, a roomnumber and a roomtype, like this:
Table-rooms
idrooms room roomtype
1 'one' 'simple'
2 'two' 'simple'
3 'three' 'double'
...
nx 'nth' 'simple'
As you can see some rooms appear multiple times, but with different periods, because they are booked on various periods.
What I need to obtain through SQL is a list of rooms that are available in a given period of time.
So something like(pseudocode):
Select room from table where there is no reservation on that room between 2015-08-13 and 2015-08-26
How can I do this?
So I will have a fromdate and a todate and I will have to use them in a query.
Can any of you guys give me some pointers please?
Right now I use the following sql to obtain a list of rooms that are available NOW
select * from rooms
where idrooms not in
(
select idroom from rezervations where
((date(now())<=dateto and date(now())>=datefrom)or(date(now())<=dateto and date(now())<=datefrom))
)
order by room
This might be easier to understand.
Assuming you have another table for rooms.
SELECT *
FROM rooms
WHERE NOT EXISTS (SELECT id
FROM reservations
WHERE reservations.room = rooms.id
AND datefrom >= '2015-08-13'
AND dateto <= '2015-08-26')
You'll want to check that records don't exist where 'date from' is less than or equal to the end date in your range and 'date to' is greater than or equal to the start date in your range.
select t1.room
from reservations t1
where not exists (
select *
from reservations t2
where t2.room = t1.room
and t2.datefrom <= '2015-08-26'
and t2.dateto >= '2015-08-13'
)
group by room
You can try it out here: http://sqlfiddle.com/#!9/cbd59/5
I'm new to the site, so it won't let me post a comment, but I think the problem on the first answer is that the operators should be reversed.
As mentioned in a previous comment, this is only good if all of the rooms have a reservation record. If not, better to select from your rooms table like this: http://sqlfiddle.com/#!9/0b96e/1
select room
from rooms
where not exists (
select *
from reservations
where rooms.room = reservations.room
and reservations.datefrom <= '2015-08-26'
and reservations.dateto >= '2015-08-13'
)
SELECT a.room
FROM yourTable a
WHERE a.room NOT IN (
SELECT DISTINCT( b.room )
FROM yourTable b
WHERE datefrom >= '2015-08-13'
OR dateto <= '2015-08-26'
);
It should work to the best of my guesses. If it doesn't; could you please provide a sqlfiddle to check the data on?
Using this SO answer
Consider
range1 : r11 r12 [inputfromDate inputToDate]
range2 : r21 r22 [datefromColumn datetoColumn]
IF r11 <= r22 && r21 <= r12, then the ranges are overlapping.
There are 6 possible case, where two ranges can overlap. But the above two condition itself handles all the 6 possibilities.
If the above condition matches then that means, the dates are overlapping. So I have used not in to get the remaining entries.
select * from <table-name> where id not in (
select id from <table-name> where
:inputfromDate <= datetoColumn and datefromColumn <= :inputToDate
)
You might try this :
select * from rooms
where room not in(
select room from reservations
where '2015-09-16' >= datefrom
and '2015-09-16' <=dateto
and '2015-09-21' >= dateto
)
Goodluck!