How to write SQL for stock quantity that requires calculation from previous orders - sql

I have two tables, one for current total stock of products and one for the product orders.
STOCK_TB
PRODUCT_ID STOCK_QTY
A 20
B 15
C 10
ORDER_TB
ORDER_DATE PRODUCT_ID ORDER QTY
2015-03-01 A 5
2015-03-02 A 3
2015-03-02 B 4
2015-03-03 C 1
2015-03-04 C 3
I'd like to select data for a monthly-stock quantity report that looks like this. Assume the report was built on March 5th
Stock Quantity of March:
Daily Stock Qty
Product ID 1 2 3 4 5 6 7 ... 28 29 30 31
A 23 20 20 20 20 0 0 0 0 0 0
B 19 15 15 15 15 0 0 0 0 0 0
C 14 14 13 10 10 0 0 0 0 0 0
The stock quantity for previous dates is based on the closing day (I.E: March 2nd above refers to March 2nd 23:59:99.999)
Any dates that goes beyond the current date will have a quantity of 0
We don't have a table for keeping daily-stocks, just the current stock. So this means for getting stocks of previous dates, I'd have to add the amount of product orders backwards.
How do you write this type of query? For the date columns, I can have them fixed from 1 to 31, since I can just hide the unused dates based on the month in my application. But I'm not really sure how I can write logic in SQL for adding order quantity to the current stock on previous dates.

Query example for 6 days (the other 25 days are the same :-)
DECLARE #FirstOfMonth AS DATETIME = DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
SELECT
CASE WHEN DAY(GETDATE()) < 1 THEN 0 ELSE S.STOCK_QTY + ISNULL((SELECT SUM(O.ORDER_QTY) FROM ORDER_TB O WHERE O.PRODUCT_ID = S.PRODUCT_ID AND O.ORDER_DATE > DATEADD(day, 0, #FirstOfMonth)), 0) END _1,
CASE WHEN DAY(GETDATE()) < 2 THEN 0 ELSE S.STOCK_QTY + ISNULL((SELECT SUM(O.ORDER_QTY) FROM ORDER_TB O WHERE O.PRODUCT_ID = S.PRODUCT_ID AND O.ORDER_DATE > DATEADD(day, 1, #FirstOfMonth)), 0) END _2,
CASE WHEN DAY(GETDATE()) < 3 THEN 0 ELSE S.STOCK_QTY + ISNULL((SELECT SUM(O.ORDER_QTY) FROM ORDER_TB O WHERE O.PRODUCT_ID = S.PRODUCT_ID AND O.ORDER_DATE > DATEADD(day, 2, #FirstOfMonth)), 0) END _3,
CASE WHEN DAY(GETDATE()) < 4 THEN 0 ELSE S.STOCK_QTY + ISNULL((SELECT SUM(O.ORDER_QTY) FROM ORDER_TB O WHERE O.PRODUCT_ID = S.PRODUCT_ID AND O.ORDER_DATE > DATEADD(day, 3, #FirstOfMonth)), 0) END _4,
CASE WHEN DAY(GETDATE()) < 5 THEN 0 ELSE S.STOCK_QTY + ISNULL((SELECT SUM(O.ORDER_QTY) FROM ORDER_TB O WHERE O.PRODUCT_ID = S.PRODUCT_ID AND O.ORDER_DATE > DATEADD(day, 4, #FirstOfMonth)), 0) END _5,
CASE WHEN DAY(GETDATE()) < 6 THEN 0 ELSE S.STOCK_QTY + ISNULL((SELECT SUM(O.ORDER_QTY) FROM ORDER_TB O WHERE O.PRODUCT_ID = S.PRODUCT_ID AND O.ORDER_DATE > DATEADD(day, 5, #FirstOfMonth)), 0) END _6
FROM STOCK_TB S
Note that I've used > DATEADD instead of >= DATEADD but I'm not so sure... The order you put the first of the month when are counted?
Second solution, but I don't think the complexity will change very much:
DECLARE #FirstOfMonth AS DATETIME = DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
DECLARE #Today AS DATETIME = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
;WITH Days(d, dat) AS
(
SELECT 1, #FirstOfMonth
UNION ALL
SELECT d+1, DATEADD(day, 1, dat) FROM Days WHERE d < DATEPART(day, #today)
)
, Work1 AS (
SELECT PRODUCT_ID, STOCK_QTY + ISNULL((SELECT SUM(O.ORDER_QTY) FROM ORDER_TB O WHERE O.PRODUCT_ID = S.PRODUCT_ID AND O.ORDER_DATE > dat), 0) STOCK_TB, d FROM STOCK_TB S, Days
)
SELECT PRODUCT_ID,
ISNULL(MAX(CASE WHEN d = 1 THEN STOCK_TB END), 0) _1,
ISNULL(MAX(CASE WHEN d = 2 THEN STOCK_TB END), 0) _2,
ISNULL(MAX(CASE WHEN d = 3 THEN STOCK_TB END), 0) _3,
ISNULL(MAX(CASE WHEN d = 4 THEN STOCK_TB END), 0) _4,
ISNULL(MAX(CASE WHEN d = 5 THEN STOCK_TB END), 0) _5,
ISNULL(MAX(CASE WHEN d = 6 THEN STOCK_TB END), 0) _6,
ISNULL(MAX(CASE WHEN d = 7 THEN STOCK_TB END), 0) _7,
ISNULL(MAX(CASE WHEN d = 8 THEN STOCK_TB END), 0) _8
FROM Work1 GROUP BY PRODUCT_ID
Here I use a fancy recursive query to build a table of days 1...(today), then I build a Work1 intermediate that has all the stock quantities day by day (so x products * y days rows), and then I group them
Third possibility: double recursive query (one to calculate the numbers 1...31 and one to do a running total), plus the final GROUP BY nearly identical to the previous example.
DECLARE #FirstOfMonth AS DATETIME = DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
DECLARE #Today AS DATETIME = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
;WITH Days(d, dat) AS
(
SELECT DATEPART(day, #Today), #Today dat
UNION ALL
SELECT d-1, DATEADD(day, -1, dat) dat
FROM Days
WHERE d > 1
)
# Product Days x STOCK_TB with a LEFT JOIN on ORDER_TB.
, Work1 AS (
SELECT S.PRODUCT_ID, d, dat, S.STOCK_QTY, ISNULL(O.ORDER_QTY, 0) ORDER_QTY
FROM Days
CROSS JOIN STOCK_TB S # Full cartesian product, JOIN without conditions
LEFT JOIN ORDER_TB O ON dat = O.ORDER_DATE AND S.PRODUCT_ID = O.PRODUCT_ID
)
# Second recursive query to do the running total
, Days2(PRODUCT_ID, d, dat, STOCK_QTY) AS
(
SELECT PRODUCT_ID, d, dat, STOCK_QTY
FROM Work1
WHERE d = DATEPART(day, #Today)
UNION ALL
SELECT d.PRODUCT_ID, d.d - 1, w.dat, d.STOCK_QTY + w.ORDER_QTY
FROM Days2 d
INNER JOIN Work1 w ON d.PRODUCT_ID = w.PRODUCT_ID AND d.d /* - 1 */ = w.d
WHERE d.d > 1
)
SELECT PRODUCT_ID,
ISNULL(MAX(CASE WHEN d = 1 THEN STOCK_QTY END), 0) _1,
ISNULL(MAX(CASE WHEN d = 2 THEN STOCK_QTY END), 0) _2,
ISNULL(MAX(CASE WHEN d = 3 THEN STOCK_QTY END), 0) _3,
ISNULL(MAX(CASE WHEN d = 4 THEN STOCK_QTY END), 0) _4,
ISNULL(MAX(CASE WHEN d = 5 THEN STOCK_QTY END), 0) _5,
ISNULL(MAX(CASE WHEN d = 6 THEN STOCK_QTY END), 0) _6,
ISNULL(MAX(CASE WHEN d = 7 THEN STOCK_QTY END), 0) _7,
ISNULL(MAX(CASE WHEN d = 8 THEN STOCK_QTY END), 0) _8
FROM Days2 GROUP BY PRODUCT_ID
Note the /* - 1 */ commented part. Uncommenting it you control how the value of the first of the month is used.

Related

My count CTE returning blanks, how can I get it return as 0?

CTE created to count the number of days left from today's date to end of current month. So my report for today (30 March 2021) did not count tomorrow's date 31 March 2021.
declare #DespatchTo Date = '03-30-2021'
WITH mycte AS
(
SELECT CAST(Convert(date,getdate()) AS DATETIME) DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue < DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, #DespatchTo) + 1, 0)) --03-31-2021
)
SELECT SUN.Count as SunCount, SAT.Count as SatCount, WK.Count as WeekCount
FROM
(SELECT count(*) as Count
FROM mycte
WHERE DatePart("w",DateValue) = 1
group by DatePart("w",DateValue))
As SUN,
(SELECT count(*) as Count
FROM mycte
WHERE DatePart("w",DateValue) = 7
group by DatePart("w",DateValue))
As SAT,
(SELECT distinct SUM(COUNT(*)) OVER() AS Count
FROM mycte
WHERE DatePart("w",DateValue) > 1 AND DatePart("w",DateValue) < 7
group by DatePart("w",DateValue))
As WK
Which returns blank/null results. How can I return as 0?
here is what you need to do:
;WITH mycte AS (
SELECT GETDATE() DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue < EOMONTH(GETDATE())
)
select
count(case when datepart(dw, DateValue) = 1 then 1 end) SUN
, count(case when datepart(dw, DateValue) = 7 then 1 end) SAT
, count(case when datepart(dw, DateValue) between 2 and 6 then 1 end) WK
from mycte
if you want to exclude today, you can adjust cte :
;WITH mycte AS (
SELECT GETDATE() + 1 DateValue
WHERE GETDATE() <> EOMONTH(GETDATE())
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue < EOMONTH(GETDATE())
)
select
count(case when datepart(dw, DateValue) = 1 then 1 end) SUN
, count(case when datepart(dw, DateValue) = 7 then 1 end) SAT
, count(case when datepart(dw, DateValue) between 2 and 6 then 1 end) WK
from mycte

How to PIVOT with 2 grouping columns in the result set?

I have a query that outputs the following:
ApptDate Truck_ID Item Qty
'8-19-20' TruckA ItemA 100
'8-19-20' TruckB ItemA 200
'8-20-20' TruckC ItemB 300
'8-20-20' TruckD ItemB 400
...
I need to PIVOT so that it returns this:
Item Truck_ID Day1 Day2 ... Day14
ItemA TruckA 100 0 0
ItemA TruckB 200 0 0
ItemB TruckC 0 300 0
ItemB TruckD 0 400 0
I tried this, but it gave an error:
Msg 8114, Level 16, State 1, Line 413
Error converting data type nvarchar to datetime.
Msg 473, Level 16, State 1, Line 413
The incorrect value "Day1" is supplied in the PIVOT operator.
select
item, truck_id, Day1, Day2, Day3, Day4, Day5, Day6, Day7, Day8, Day9, Day10, Day11, Day12, Day13, Day14
from(
select
ds.ApptDate
, c.truck_id
, c.item
, sum(c.qty) qty
from
maintable c with(nolock)
inner join secondtable ds with(nolock) on c.truck_id = ds.truckid and ds.type = 'O'
where
ds.apptdate between cast(getdate() as date) and dateadd(day, 14, cast(getdate() as date))
and coalesce(ds.CancelTruck, 0) <> 1
and ds.Status <> '5'
group by
c.truck_id
, c.item
, ds.ApptDate
) sourcetable
pivot
(
sum(qty)
for apptdate in ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14])
) as pivottable
Since you expect a fixed number of columns, we don't necessarily need dynamic SQL. One option uses conditional aggregation... and lot of repeated typing:
select
item,
truck_id,
sum(case when appt_date = cast(getdate() as date) then qty else 0 end) day0,
sum(case when appt_date = dateadd(day, -1 , cast(getdate() as date)) then qty else 0 end) day1,
sum(case when appt_date = dateadd(day, -2 , cast(getdate() as date)) then qty else 0 end) day2,
...
sum(case when appt_date = dateadd(day, -14, cast(getdate() as date)) then qty else 0 end) day14
from ( -- your current query here --) t
group by item, truck_id
This approach uses datediff's on the minimum date and the AppDate.
;with
min_dt_cte(min_dt) as (select min(cast(AppDate as date)) from MyTable),
pvt_dt_cte(ApptDate, Truck_ID, Item, Qty, DayNum) as (
select t.*, datediff(d, mdc.min_dt, cast(AppDate as date))
from min_dt_cte mdc
cross join
MyTable t)
select
pdc.Item, pdc.Truck_ID,
iif(pdc.DayNum=1, Qty, 0) Day1,
iif(pdc.DayNum=2, Qty, 0) Day2,
...
iif(pdc.DayNum=14, Qty, 0) Day14
from
pvt_dt_cte pdc;

Quantity of data per month

I have to calculate the number of cars a day - of every month
I tried to do this using the Datediff formula
But I can't add the segmentation of each month either.
Attached script table:
create table TABLE_A(Code FLOAT,DateIn datetime,dateOut datetime,Garage varchar(30)
)
insert into Table_A (Code,DateIn,dateOut,Garage) values
('1','2018-06-07 00:00:00.000','2018-12-19 00:00:00.000','X'),
('2','2018-05-30 00:00:00.000','2018-12-19 00:00:00.000','Y'),
('3','2018-08-08 00:00:00.000','2018-11-18 00:00:00.000','Z'),
('4','2018-12-30 00:00:00.000','2018-12-30 00:00:00.000','Y'),
('5','2018-09-16 00:00:00.000','2018-10-19 00:00:00.000','Y'),
('6','2018-05-08 00:00:00.000','2018-08-28 00:00:00.000','Z'),
('7','2018-01-29 00:00:00.000','2018-07-31 00:00:00.000','Z'),
('8','2018-05-24 00:00:00.000','2018-09-10 00:00:00.000','X'),
('9','2018-05-02 00:00:00.000','2018-06-30 00:00:00.000','Y'),
('10','2018-07-05 00:00:00.000','2018-12-09 00:00:00.00','Z')
And this is the structure of the query result that should be:(Columns:Year,month,Garage-Number of vehicles per day by month)
Year month X Y Z
2018 1
2018 2
2018 3
2018 4
2018 5
2018 6
2018 7
2018 8
2018 9
2018 10
2018 11
2018 12
Thanks for the help.
You can first generate the list of months and year and then can left join your table to that -
WITH MONTHS AS (SELECT 1 MNTHS
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
UNION ALL
SELECT 7
UNION ALL
SELECT 8
UNION ALL
SELECT 9
UNION ALL
SELECT 10
UNION ALL
SELECT 11
UNION ALL
SELECT 12),
YEAR AS (SELECT 2018 YEAR)
SELECT YEAR,
MNTHS,
SUM(CASE WHEN Garage = 'X' THEN 1 ELSE 0 END) AS X,
SUM(CASE WHEN Garage = 'Y' THEN 1 ELSE 0 END) AS Y,
SUM(CASE WHEN Garage = 'Z' THEN 1 ELSE 0 END) AS Z
FROM (SELECT * FROM MONTHS M CROSS JOIN YEAR Y) YEARS
LEFT JOIN TABLE_A T ON YEARS.MNTHS = MONTH(T.DateIn)
AND YEARS.YEAR = YEAR(T.DateIn)
GROUP BY YEAR(DateIn),
MONTH(DateIn),
MNTHS,
YEAR
ORDER BY YEAR,
MNTHS
Here is the fiddle
The following query should do what you want, the Recursive CTE part is used to figure out dates between each DayIn and DayOut. Once we have the complete list of dates, in the main query we do a conditional aggregation to find out the DISTINCT number of cars in the garage each month,
CREATE TABLE TABLE_A (Code FLOAT,DateIn DATETIME,dateOut DATETIME,Garage VARCHAR(30))
INSERT INTO Table_A (Code,DateIn,dateOut,Garage) VALUES
('1','2018-06-07 00:00:00.000','2018-12-19 00:00:00.000','X'),
('2','2018-05-30 00:00:00.000','2018-12-19 00:00:00.000','Y'),
('3','2018-08-08 00:00:00.000','2018-11-18 00:00:00.000','Z'),
('4','2018-12-30 00:00:00.000','2018-12-30 00:00:00.000','Y'),
('5','2018-09-16 00:00:00.000','2018-10-19 00:00:00.000','Y'),
('6','2018-05-08 00:00:00.000','2018-08-28 00:00:00.000','Z'),
('7','2018-01-29 00:00:00.000','2018-07-31 00:00:00.000','Z'),
('8','2018-05-24 00:00:00.000','2018-09-10 00:00:00.000','X'),
('9','2018-05-02 00:00:00.000','2018-06-30 00:00:00.000','Y'),
('10','2018-07-05 00:00:00.000','2018-12-09 00:00:00.00','Z')
/** Main Query Starts Here **/
;WITH CTE ([Code],[DateIn],[DateOut],[Garage]) AS (
SELECT [Code], [DateIn], [DateOut], [Garage]
FROM TABLE_A WHERE [DateIn] <= [DateOut]
UNION ALL
SELECT [Code], DATEADD(DAY, 1, [DateIn]), [DateOut], [Garage]
FROM CTE
WHERE [DateIn] < [DateOut])
SELECT
YEAR([DateIn]) AS [Year]
,MONTH([DateIn]) AS [Month]
,COUNT( DISTINCT CASE WHEN [Garage] = 'X' THEN T.t1 ELSE NULL END) AS X
,COUNT( DISTINCT CASE WHEN [Garage] = 'Y' THEN T.t1 ELSE NULL END) AS Y
,COUNT( DISTINCT CASE WHEN [Garage] = 'Z' THEN T.t1 ELSE NULL END) AS Z
FROM CTE
CROSS APPLY (VALUES (CONVERT(VARCHAR(4),YEAR([DateIn])) + CONVERT(VARCHAR(2),MONTH([DateIn])) + CONVERT(VARCHAR(20),[Code]))) AS T(t1)
GROUP BY YEAR([DateIn]), MONTH([DateIn])
ORDER BY [Year], [Month]
OPTION (MAXRECURSION 0)
The result is as below,
Year Month X Y Z
2018 1 0 0 1
2018 2 0 0 1
2018 3 0 0 1
2018 4 0 0 1
2018 5 1 2 2
2018 6 2 2 2
2018 7 2 1 3
2018 8 2 1 3
2018 9 2 2 2
2018 10 1 2 2
2018 11 1 1 2
2018 12 1 2 1
You can generate the dates using a recursive subquery.
Then you have multiple ways to calculate the summary data. One simple method uses apply:
with dates as (
select convert(date, '2018-01-01') as dte, 1 as lev
union all
select dateadd(month, 1, dte), lev + 1
from dates
where lev < 12
)
select year(d.dte), month(d.dte), s.*
from dates d outer apply
(select sum(case when a.Garage = 'X' then 1 else 0 end) as x,
sum(case when a.Garage = 'Y' then 1 else 0 end) as y,
sum(case when a.Garage = 'Z' then 1 else 0 end) as z
from table_a a
where a.datein <= d.dte and a.dateout >= d.dte
) s;
Your question is a little vague on the exact calculation. This calculates the number of cars in each garage on the first of each month.
Here is a db<>fiddle.
EDIT:
Your revised question is more complicated, but since I started answering:
with dates as (
select convert(date, '2018-01-01') as dte, 1 as lev
union all
select dateadd(month, 1, dte), lev + 1
from dates
where lev < 12
)
select year(d.dte), month(d.dte),
sum(case when a.Garage = 'X'
then datediff(day,
(case when a.datein < d.dte then d.dte else datein end),
(case when a.dateout >= dateadd(month, 1, d.dte) then eomonth(d.dte) else dateout end)
) + 1
else 0
end) as x_cardays,
sum(case when a.Garage = 'Y'
then datediff(day,
(case when a.datein < d.dte then d.dte else datein end),
(case when a.dateout >= dateadd(month, 1, d.dte) then eomonth(d.dte) else dateout end)
) + 1
else 0
end) as y_cardays,
sum(case when a.Garage = 'Z'
then datediff(day,
(case when a.datein < d.dte then d.dte else datein end),
(case when a.dateout >= dateadd(month, 1, d.dte) then eomonth(d.dte) else dateout end)
) + 1
else 0
end) as z_cardays
from (select d.*, day(eomonth(dte)) as days_in_month
from dates d
) d left join
table_a a
on a.datein < dateadd(month, 1, d.dte) and a.dateout >= d.dte
group by d.dte
order by d.dte;
Overlaps with dates are a bit tricky, but you definitely want to do this with dates.
Note this doesn't calculate the average per day. You can divide by d.days_in_month if you want the average.
Here is a revised db<>fiddle.
This below script will only work if all your DateIn and DateOut for a particular record is in a single year like 2018.
Leap year Year is not considered but can be implemented.
WITH Month_Wise_Day AS
(
-- Listing/selecting 12 month manually here
-- With number of day for that month
SELECT 1 M, 31 ND UNION ALL
SELECT 2 M, 28 UNION ALL SELECT 3 M,31 UNION ALL SELECT 4 M,30 UNION ALL SELECT 5 M,31 UNION ALL
SELECT 6 M,30 UNION ALL SELECT 7 M,31 UNION ALL SELECT 8 M,31 UNION ALL SELECT 9 M,30 UNION ALL
SELECT 10 M,31 UNION ALL SELECT 11 M,30 UNION ALL SELECT 12 M,31
)
SELECT A.Year, A.Month,
SUM(CASE WHEN A.Garage = 'X' THEN A.No_of_days ELSE 0 END) AS X,
SUM(CASE WHEN A.Garage = 'Y' THEN A.No_of_days ELSE 0 END) AS Y,
SUM(CASE WHEN A.Garage = 'Z' THEN A.No_of_days ELSE 0 END) AS Z
FROM
(
SELECT A.*,
B.M AS Month,
YEAR(A.DateIn) AS Year,
CASE
WHEN MONTH(A.DateIn) = MONTH(A.DateOut) THEN DATEDIFF(DD,DateIn,DateOut) +1
WHEN B.M = MONTH(DateIn) THEN B.ND - DAY(DateIn)+1
WHEN B.M = MONTH(DateOut) THEN DAY(DateOut)
ELSE ND
END No_of_days
FROM TABLE_A A
INNER JOIN Month_Wise_Day B ON B.M BETWEEN MONTH(DateIn) AND MONTH (DateOut)
)A
GROUP BY A.Year, A.Month

Data according to time

I have table1 in this data is
ID Name StartDate EndDate
1 Paris 2014-02-01 00:00:00.000 2014-02-28 23:59:59.000
2 UK 2014-02-01 00:00:00.000 2014-02-28 23:59:59.000
3 France 2014-02-01 00:00:00.000 2014-02-28 23:59:59.000
and sp is
ALTER procedure [dbo].[spdata]
#fromdate datetime,
#todate datetime,
#Region varchar(50)
as
Select (Select Sum(Convert(int,SF)) from RVU inner dbo.VI vh on RVU.FID = vh.FID WHERE vh.No = Q.No and ID in (
Select ID from RU WHERE CAST(StartDate as date)>= CAST(#fromdate as date) and CAST(EndDate as date)<= CAST(#todate as date)
)) as SF
from (
Select
S.Name,
S.No,
SUM(Case when s.Vme='Car' then total else 0 end) as CAR,
SUM(Case when s.Vme='Tin' then total else 0 end) as Tin,
SUM(Case when s.Vme='Cake' then total else 0 end) as Cake,
SUM(Case when s.Vme='Flow' then total else 0 end) as Flow,
SUM(Case when s.Vme='Unit' then total else 0 end) as Unit,
SUM(total) total ,
MAX(S.Speed) Speed
from (
Select vh.Name as Name,vh.No as No,VV.Vame,count(VV.Vme) as total, RV.SF as MA,
RV.Speed from VVU VV inner join RVU RV on VV.MID=RV.ID inner join RU RU on RV.ID=RU.ID
left join dbo.VI vh on RV.FID = vh.FID WHERE CAST(RU.StartDate as date)>= CAST(#fromdate as date) and CAST(RU.EndDate as date)<= CAST(#todate as date) and
RU.Name_C= #Name_C AND Vme <> '' Group By vh.Name, vh.No, VV.Vme, RV.SF,
RV.Speed ) S GROUP BY s.RegNo, s.Name) Q
from that sp when i enter parameters DATA IS
[spdata] '2016-07-01 00:00:00.000', '2016-07-31 23:59:59.000', 'pARIS'
Name No CAR Tin Cake Flow Unit total Speed SF
John 412 0 0 12 0 5 17 82 60
Mike 48 2 1 5 1 3 9 160 464
ACNme 438 0 1 5 2 3 11 10 264
XYZ 248 0 1 5 3 3 12 60 244
now i want when i change time '2016-07-01 00:00:00.000', '2016-07-31 23:59:59.000',
like this
'2016-07-01 02:02:00.000', '2016-07-31 12:59:59.000',
then records also reflect on this time means according to date plus time data will be display
Don't cast your StartDate , EndDate , #fromdate , #todate as Date.
`Alter procedure [dbo].[spdata]
#fromdate datetime,
#todate datetime,
#Region varchar(50)
as
Select (Select Sum(Convert(int,SF)) from RVU inner dbo.VI vh on RVU.FID = vh.FID WHERE vh.No = Q.No and ID in (
Select ID from RU WHERE StartDate >= #fromdate and EndDate <=#todate
)) as SF
from (
Select
S.Name,
S.No,
SUM(Case when s.Vme='Car' then total else 0 end) as CAR,
SUM(Case when s.Vme='Tin' then total else 0 end) as Tin,
SUM(Case when s.Vme='Cake' then total else 0 end) as Cake,
SUM(Case when s.Vme='Flow' then total else 0 end) as Flow,
SUM(Case when s.Vme='Unit' then total else 0 end) as Unit,
SUM(total) total ,
MAX(S.Speed) Speed
from (
Select vh.Name as Name,vh.No as No,VV.Vame,count(VV.Vme) as total, RV.SF as MA,
RV.Speed from VVU VV inner join RVU RV on VV.MID=RV.ID inner join RU RU on RV.ID=RU.ID
left join dbo.VI vh on RV.FID = vh.FID WHERE RU.StartDate >= #fromdate and RU.EndDate <= #todate and
RU.Name_C= #Name_C AND Vme <> '' Group By vh.Name, vh.No, VV.Vme, RV.SF,
RV.Speed
) S GROUP BY s.RegNo, s.Name) Q`

SQL- Date Diff- # of week in each month between two date periods

Problem: Display in columns the number of weeks in each month between two date periods (out to three months is fine for now). If possible, from the current day (Dynamic)
Where I currently am:
SELECT Q3.[Begin Date]
,Q3.[End Date]
,Q3.Diff_in_Year
,sum(CASE
WHEN Q3.Year_Counter = 0
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y1
,sum(CASE
WHEN Q3.Year_Counter = 1
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y2
,sum(CASE
WHEN Q3.Year_Counter = 2
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y3
,sum(CASE
WHEN Q3.Year_Counter = 3
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y4
,sum(CASE
WHEN Q3.Year_Counter = 4
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y5
,sum(CASE
WHEN Q3.Year_Counter = 5
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y6
,sum(CASE
WHEN Q3.Year_Counter = 6
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y7
,sum(CASE
WHEN Q3.Year_Counter = 7
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y8
,sum(CASE
WHEN Q3.Year_Counter = 8
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y9
,sum(CASE
WHEN Q3.Year_Counter = 9
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y10
FROM (
SELECT Q1.[Begin Date]
,Q1.[End Date]
,Q1.years Diff_in_Year
,Q2.number AS Year_Counter
,(
CASE
WHEN Q2.number = 0
THEN Q1.[Begin Date]
ELSE dateadd(yy, datediff(yy, 0, dateadd(yy, q2.number, q1.[Begin Date])), 0)
END
) AS y_Start
,(
CASE
WHEN ((Q1.years - 1) = Q2.number)
THEN Q1.[End Date]
ELSE DATEADD(yy, DATEDIFF(yy, 0, dateadd(yy, q2.number + 1, q1.[Begin Date]) + 1), - 1)
END
) AS y_End
,Year(Q1.[Begin Date]) + Q2.number YearInYYYY
FROM (
SELECT [Begin Date]
,[End Date]
,DATEDIFF(year, [Begin Date], [End Date]) + 1 AS years
FROM my dates
) Q1
INNER JOIN master..spt_values Q2 ON Q2.type = 'P'
AND Q2.number < Q1.years
) Q3
GROUP BY Q3.[Begin Date]
,Q3.[End Date]
,q3.Diff_in_Year
How the current code works: Given a date range, the number of months in each year between two dates. IE 1/1/2014 - 1/18/2015 would give two columns "2014" and 2015" the value of 2014 is 12 and the value of 2015 is 1 signifying that there are 13 months between the specified dates.
What I am hoping to achieve is something similar to
Start Date End Date Month 1 Month 2 Month 3
-----------------------------------------------------
1/1/2014 3/8/2014 4 4 1
Dynamic SQL solutions aside (search for dynamic pivot in TSQL), I whipped up a couple of answers. Since your question is unclear whether you want weeks or months, I put together a quick one for each.
Months Example Here:
declare #startdate date = '1/1/2014', #enddate date = '3/1/2015'
select p.*
from (
select #startdate as StartDate, #enddate as EndDate, right(convert(varchar,(dateadd(mm,RowID-1,#startdate)),105),4) [Group]
from (
select *, row_number()over(order by name) as RowID
from master..spt_values
) d
where d.RowID <= datediff(mm, #startdate, #enddate)
) t
pivot (
count([Group]) for [Group] in (
[2014],[2015]
)
) p
Weeks Example Here:
declare #startdate date = '1/1/2014', #enddate date = '3/1/2015'
select p.*
from (
select #startdate as StartDate, #enddate as EndDate, right(convert(varchar,(dateadd(ww,RowID-1,#startdate)),105),7) [Group]
from (
select *, row_number()over(order by name) as RowID
from master..spt_values
) d
where d.RowID <= datediff(ww, #startdate, #enddate)
) t
pivot (
count([Group]) for [Group] in (
[01-2014]
, [02-2014]
, [03-2014]
, [04-2014]
, [05-2014]
, [06-2014]
, [07-2014]
, [08-2014]
, [09-2014]
, [10-2014]
, [11-2014]
, [12-2014]
, [01-2015]
, [02-2015]
, [03-2015]
)
) p