How to partially Match cell against another partial cell - sql

I have a problem with two tables which I need to compare dates for the same reference. The problem is that
the dates are different formats and
superfluous data is also contained within both date cells.
Global
No. Date
1 1992-08-25 00:00:00.000
2 2015-05-19 00:00:00.000
3 2000-01-12 00:00:00.000
Local
No. Date
1 25.08.1992 00:00:00.000000000 GMT
1 28.08.1992 00:00:00.000000000 GMT
2 19.05.2015 00:00:00.000000000 GMT
3 12.01.2000 00:00:00.000000000 GMT
3 17.01.2000 00:00:00.000000000 GMT
Note that the date formats between the two tables differ and contain lots of time and zero data that is not needed. So ideally I would like to see the format as DD-MM-YYYY.
I would like to return only the Global and Local entries where the Local date differs from Global date. So from the data above, I would want to see:
No. Date No. Date
1 25-08-1992 1 28-08-1992
3 12-01-2000 3 17-01-2000
I would put my attempts so far, but to be honest I have no idea on how to tackle the partial cell matching and re-formatting.
Any ideas?
Update:
I tried a solution from #Sarslan and substituted my table and field names which resulted in this:
WITH G AS
(
SELECT [UPC], CONVERT(DATE,LEFT([GLOBAL RELEASE DATE], CHARINDEX(' ',
[GLOBAL RELEASE DATE])),120) [Date] FROM [dsched_migration].[emi].
[EMI_Global]
)
,L AS
(
SELECT [UPC], CONVERT(DATE,LEFT([TERR_REL_DATE], CHARINDEX(' ',
[TERR_REL_DATE])),104) [Date] FROM [dsched_migration].[emi].
[terr_release_dates]
)
SELECT
G.UPC, CONVERT(VARCHAR,G.Date,105) [GLOBAL RELEASE DATE],
L.UPC, CONVERT(VARCHAR,L.Date,105) [TERR_REL_DATE]
FROM
G INNER JOIN L ON L.UPC = G.UPC
WHERE L.Date <> G.Date
I keep getting this error:
Msg 241, Level 16, State 1, Line 7
Conversion failed when converting date and/or time from character string.

select * from
(
select a.no, to_char(a.date,'DD-mm-YYY') Date1 , b.no, to_char(b.date,'DD-mm-YYY') Date2
from Global a inner join Local b on (a.no=b.no)
)
where Date1<>Date2;

Could you try this?
;WITH G AS
(
SELECT [No], CONVERT(DATE,LEFT([Date], CHARINDEX(' ', [Date])),120) [Date] FROM [GLobal]
)
,L AS
(
SELECT [No], CONVERT(DATE,LEFT([Date], CHARINDEX(' ', [Date])),104) [Date] FROM [Local]
)
SELECT
G.No, CONVERT(VARCHAR,G.Date,105) [Date],
L.No, CONVERT(VARCHAR,L.Date,105) [Date]
FROM
G INNER JOIN L ON L.No = G.No
WHERE L.Date <> G.Date
Result
No Date No Date
----------- ------------------------------ ----------- ------------------------------
1 25-08-1992 1 28-08-1992
3 12-01-2000 3 17-01-2000

When you have some formatted string that format will never change you can simplify it like this - this will also give you more flexibility -:
;with tg as (
select [No],
-- Format is : yyyy-mm-dd
left([Date], 4) yyyy, substring([Date], 6, 2) mm, substring([Date], 9, 2) dd
from g
), tl as (
select [No],
-- Format is: dd-mm-yyyy
substring([Date], 7, 4) yyyy, substring([Date], 4, 2) mm, left([Date], 2) dd
from l
)
select *
from tg
inner join tl
on tg.[No] = tl.[No]
and not (tg.yyyy = tl.yyyy and tg.mm = tl.mm and tg.dd = tl.dd);

Thanks for all replies but found a solution:
Created a new column then ran this query to confirm the conversion:
SELECT '19.10.2009 00:00:00.000000000 GMT',
CONVERT(datetime, LEFT('19.10.2009 00:00:00.000000000 GMT',10), 104)
This gave me the right format then I ran the following query to update the new column with the formatted date:
update LocalDate
set REL_DATE = CONVERT(datetime, LEFT(TERR_REL_DATE,10), 104)
Luckily my Global date was already in datetime so I then simply joined the two tables and ran my comparison against the new updated time

Related

Dynamically SELECT a column based on value of row at first of month

The following query:
SELECT Confirmed, Interim, Declared, Date
FROM Interest_Hist
WHERE Date BETWEEN '2019-08-01' AND '2019-12-04'
ORDER BY Date ASC
Returns the following sample data:
Confirmed Interim Declared Date
Y 0.314 0.0788 2019-08-01
0.317 0 2019-08-02
...
0.245 0 2019-08-31
0.222 0.219 2019-09-01
0.198 0 2019-09-02
...
Y 0.50 0.454 2019-12-01
0.51 0 2019-12-02
0.52 0 2019-12-03
0.53 0 2019-12-04
Where on the first of the month, Confirmed = Y, I need to return the Declared column for that month.
Note, Confirmed = Y will only exist on the first of the month. That column is blank in all other cases
Otherwise, I need to return each Interim column for the month.
Thus far, I have been able to return the SUM of either column, but not the individual values.
SELECT
CASE WHEN SUM(CASE WHEN IRc_Confirmed = 'Y' THEN 1 ELSE 0 END) = 0
THEN Interim
ELSE Declared
END AS Rate
FROM Fund_Interest
WHERE Date BETWEEN '2019-08-01' AND '2019-12-04'
GROUP BY
DATEADD(month, DATEDIFF(month, 0, Date), 0), Interim, Declared
ORDER BY
DATEADD(month, DATEDIFF(month, 0, Date), 0)
The expected output given the data at the top is as follows
0.0788
0
...
0
0.222
0.198
...
0.454
0
0
0
Find all the year months where the first day is Y:
SELECT year([date]) as yr, month([date]) as mo
FROM fund_interest
WHERE DAY([date]) = 1 and confirmed = 'Y'
This gives you a list of years and months where there is a Y on the first eg Aug 2019
Now make it a cte and left join it back to your data on year and month, and where the join succeeds return declared else interim:
WITH x AS(
SELECT year([date]) as yr, month([date]) as mo
FROM fund_interest
WHERE DAY([date]) = 1 and confirmed = 'Y'
)
SELECT
CASE WHEN x.yr IS NOT NULL THEN f.declared ELSE f.interim END AS something
FROM
fund_interest f
LEFT OUTER JOIN x ON x.yr = year(f.[date]) AND x.mo = month(f.[date])
All of the rows of different days from Aug 2019 and Dec 2019 will succeed in the join. They will have a NOT NULL yr value and hence the declared will show. For all Sep 2019 rows there is no match in the join (Sep 2019 is not returned by the query in the CTE), yr is null, interim shows instead
For a better idea of what is going on do a SELECT *
If you want to use just a single column the EOMONTH function could be used to return a consistent date every month. Replace MONTH with EOMONTH. Remove calls to YEAR from the query
Do not use reserved words like DATE as column names, by the way
You can use a CTE to group by month and year and then join to your original table (Interest_Hist) on the month and year parts of your date field. You can then select the Interim or Declared value using a simple case statement
;WITH CTE AS
(
SELECT DATEPART(month, DateFld) Mnth, DATEPART(year, DateFld) Yr,
MAX(Confirmed) ConfirmedVal
FROM Interest_Hist
GROUP BY DATEPART(month, DateFld), DATEPART(year, DateFld)
)
SELECT
CASE WHEN c.ConfirmedVal= 'Y' THEN interest.Declared ELSE interest.Interim END
FROM Interest_Hist interest
INNER JOIN CTE c ON
DATEPART(month, interest.DateFld) = c.Mnth AND
DATEPART(year, interest.DateFld) = c.Yr
You can see the query in action here
This took me way longer than it probably should have.
SELECT IIF( MAX(Confirmed) OVER(PARTITION BY CONVERT(VARCHAR(6), Date, 112)) = 'Y', Declared, Interim) Interest_Rate
FROM Interest_Hist
WHERE DateBETWEEN '01-AUG-2019' AND '04-DEC-2019'
ORDER BY Date

How to convert text to date entered as a date in sql?

Data type is TEXT and entered as '20/11/2017' and when using MAX or MIN it ignores the month. I am trying to convert it into a date format for month to be considered as well.
CAST AND CONVERT do not seem to work as the following error returns
Msg 241, Level 16, State 1, Line 13
Conversion failed when converting date and/or time from character string.
Code:
SELECT
user_id,
record_id
--CAST(onSale AS date) AS onSale
--CONVERT(DATE, onSale) AS onSale,
--CONVERT(DATE, OffSale) AS OffSale
FROM (SELECT user_id,
record_id,
(SELECT MAX(value) AS Expr1
FROM UPLOADS.LINES AS SUH WITH (NoLock, ReadUncommitted)
WHERE (field_id = 4782) AND (record_id = UR.record_id)) AS onSale,
(SELECT MAX(value) AS Expr1
FROM UPLOADS.LINES AS SUH WITH (NoLock, ReadUncommitted)
WHERE (field_id = 4783) AND (record_id = UR.record_id)) AS OffSale
FROM UPLOADS.RECORDS AS UR WITH (NoLock, ReadUncommitted)
WHERE (module_id = 18)) AS DATA;
The end result would essentially be the MAX or MIN date with all three components being date,month and year. So if the user has entered two dates being 17/05/2018 and 17/04/2018 then the first should be shown if MAX is used.
You can use a format code when using CONVERT, and you can even use TRY_CONVERT to prevent errors from invalid dates. I also improved your code to make it simpler and more efficient.
SELECT [user_id],
record_id,
MAX(CASE WHEN SUH.field_id = 4782 THEN TRY_CONVERT( DATE, SUH.value, 103) END) AS onSale,
MAX(CASE WHEN SUH.field_id = 4783 THEN TRY_CONVERT( DATE, SUH.value, 103) END) AS OffSale
FROM UPLOADS.RECORDS AS UR
JOIN UPLOADS.LINES AS SUH ON SUH.record_id = UR.record_id
WHERE module_id = 18
GROUP BY [user_id],
record_id;
This is a slight improvement on Luis's answer in terms of the SQL:
SELECT ur.[user_id], ur.record_id,
MAX(CASE WHEN SUH.field_id = 4782 THEN TRY_CONVERT( DATE, SUH.value, 103) END) AS onSale,
MAX(CASE WHEN SUH.field_id = 4783 THEN TRY_CONVERT( DATE, SUH.value, 103) END) AS OffSale
FROM UPLOADS.RECORDS UR LEFT JOIN
UPLOADS.LINES AS SUH
ON SUH.record_id = UR.record_id AND
SUH.field_id IN (4782, 4783)
WHERE ur.module_id = 18
GROUP BY ur.[user_id], ur.record_id;
That said, your problem is that your data is not in the format you think it is. Hence, the problem with type conversions. As #marc_s says in a comment, you should be using SQL native and appropriate types which in this case is DATE. And you certainly should not be using deprecated types, such as TEXT (unless you really just mean VARCHAR() and don't realize that there is a deprecated TEXT type). If you are storing values in strings (because there are different types), you should use the standard format, either YYYYMMDD or YYYY-MM-DD.
You can find these values by running:
select suh.value
from uploads.lines suh
where suh.field_id in (4782, 4783) and
try_convert(date, suh.value, 103) is null and
suh.value is not null;
This can help you fix your data.
After you have fixed your data, you can also fix the type:
update uploads.lines
set suh.value = convert(varchar(255), convert(date, suh.value, 103), 112); -- this will convert the value to the default date format

SQL - Value difference between specific rows

My query is as follows
SELECT
LEFT(TimePeriod,6) Period, -- string field with YYYYMMDD
SUM(Value) Value
FROM
f_Trans_GL
WHERE
Account = 228
GROUP BY
TimePeriod
And it returns
Period Value
---------------
201412 80
201501 20
201502 30
201506 50
201509 100
201509 100
I'd like to know the Value difference between rows where the period is 1 month apart. The calculation being [value period] - [value period-1].
The desired output being;
Period Value Calculated
-----------------------------------
201412 80 80 - null = 80
201501 20 20 - 80 = -60
201502 30 30 - 20 = 10
201506 50 50 - null = 50
201509 100 (100 + 100) - null = 200
This illustrates a second challenge, as the period needs to be evaluated if the year changes (the difference between 201501 and 201412 is one month).
And the third challenge being a duplicate Period (201509), in which case the sum of that period needs to be evaluated.
Any indicators on where to begin, if this is possible, would be great!
Thanks in advance
===============================
After I accepted the answer, I tailored this a little to suit my needs, the end result is:
WITH cte
AS (SELECT
ISNULL(CAST(TransactionID AS nvarchar), '_nullTransactionId_') + ISNULL(Description, '_nullDescription_') + CAST(Account AS nvarchar) + Category + Currency + Entity + Scenario AS UID,
LEFT(TimePeriod, 6) Period,
SUM(Value1) Value1,
CAST(LEFT(TimePeriod, 6) + '01' AS date) ord_date
FROM MyTestTable
GROUP BY LEFT(TimePeriod, 6),
TransactionID,
Description,
Account,
Category,
Currency,
Entity,
Scenario,
TimePeriod)
SELECT
a.UID,
a.Period,
--a.Value1,
ISNULL(a.Value1, 0) - ISNULL(b.Value1, 0) Periodic
FROM cte a
LEFT JOIN cte b
ON a.ord_date = DATEADD(MONTH, 1, b.ord_date)
ORDER BY a.UID
I have to get the new value (Periodic) for each UID. This UID must be determined as done here because the PK on the table won't work.
But the issue is that this will return many more rows than I actually have to begin with in my table. If I don't add a GROUP BY and ORDER by UID (as done above), I can tell that the first result for each combination of UID and Period is actually correct, the subsequent rows for that combination, are not.
I'm not sure where to look for a solution, my guess is that the UID is the issue here, and that it will somehow iterate over the field... any direction appreciated.
As pointed by other, first mistake is in Group by you need to Left(timeperiod, 6) instead of timeperiod.
For remaining calculation try something like this
;WITH cte
AS (SELECT LEFT(timeperiod, 6) Period,
Sum(value) Value,
Cast(LEFT(timeperiod, 6) + '01' AS DATE) ord_date
FROM f_trans_gl
WHERE account = 228
GROUP BY LEFT(timeperiod, 6))
SELECT a.period,
a.value,
a.value - Isnull(b.value, 0)
FROM cte a
LEFT JOIN cte b
ON a.ord_date = Dateadd(month, 1, b.ord_date)
If you are using SQL SERVER 2012 then this can be easily done using LAG analytic function
Using a derived table, you can join the data to itself to find rows that are in the preceding period. I have converted your Period to a Date value so you can use SQL Server's dateadd function to check for rows in the previous month:
;WITH cte AS
(
SELECT
LEFT(TimePeriod,6) Period, -- string field with YYYYMMDD
CAST(TimePeriod + '01' AS DATE) PeriodDate
SUM(Value) Value
FROM f_Trans_GL
WHERE Account = 228
GROUP BY LEFT(TimePeriod,6)
)
SELECT c1.Period,
c1.Value,
c1.Value - ISNULL(c2.Value,0) AS Calculation
FROM cte c1
LEFT JOIN cte c2
ON c1.PeriodDate = DATEADD(m,1,c2.PeriodDate)
Without cte, you can also try something like this
SELECT A.Period,A.Value,A.Value-ISNULL(B.Value) Calculated
FROM
(
SELECT LEFT(TimePeriod,6) Period
DATEADD(M,-1,(CONVERT(date,LEFT(TimePeriod,6)+'01'))) PeriodDatePrev,SUM(Value) Value
FROM f_Trans_GL
WHERE Account = 228
GROUP BY LEFT(TimePeriod,6)
) AS A
LEFT OUTER JOIN
(
SELECT LEFT(TimePeriod,6) Period
(CONVERT(date,LEFT(TimePeriod,6)+'01')) PeriodDate,SUM(Value) Value
FROM f_Trans_GL
WHERE Account = 228
GROUP BY LEFT(TimePeriod,6)
) AS B
ON (A.PeriodDatePrev = B.PeriodDate)
ORDER BY 1

How can I get 3 names to repeat for every date in a date range?

This is my first question here so I apologize if I do something wrong. I am also an SQL amateur so sorry if i don't make any sense. I am working with SQL Server 2014.
I have dates in a date range (11/01/15 to 11/30/15) and I have 3 location names : NY, LA, SF. Can I get each of those names to show up in a seperate row for each date in the range?
Something like this:
11/01/15 | NY
11/01/15 | LA
11/01/15 | SF
11/02/15 | NY
11/02/15 | LA
11/02/15 | SF
11/03/15 | NY
11/03/15 | LA
11/03/15 | SF
.
.
.
.
11/30/15 | NY
11/30/15 | LA
11/30/15 | SF
Seeing your CTE:
WITH mycte
AS
(
SELECT CAST('20151101' AS DATETIME
) DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue + 1 < '20151201'
),
myNames
(myName
)
AS
(
SELECT 'NY'
UNION
SELECT 'LA'
UNION
SELECT 'SF'
)
SELECT *
FROM mycte m
CROSS JOIN myNames mn;
Assuming dates are in a table called myDates and names are in a table called myNames with fieldnames myDate and myName respectively:
select d.myDate, n.myName
from myDates d
cross join myNames n
where d.MyDate >= '20151101' and d.myDate < '20151201'
Try this:
DECLARE #StartDate DATE = '20150111'
DECLARE #EndDate DATE = '20151130'
DECLARE #Diff INT = DATEDIFF(DAY, #StartDate, #EndDate)
PRINT #Diff
;WITH DateRangeCte AS (
SELECT DATEADD(DAY, currDay - 1, #StartDate) AS RangeDate
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS currDay
-- this table should have more records than range size
FROM sys.messages
) nbrs
WHERE currDay - 1 <= #Diff
)
SELECT RangeDate, LocationName
FROM DateRangeCte C
CROSS JOIN (
SELECT 'NY' AS LocationName UNION ALL
SELECT 'LA' UNION ALL
SELECT 'SF'
) Loc
go
As suggested, DateRangeCte can be generated using a recursive CTE or by iterating through a "big enough" table (number of rows is known to be larger than interval size). I have chosen sys.message since it is quite big (more than 200K), but it will have an impact upon performance. If performance is important, choose recursive CTE (st33vemcqu33n's answer).
Also, I have CROSS JOINed with an "anonymous" table. I guess those states will be stored in a persistent table, so you will cross join with that table.

SQL Case select

maybe someone can help me
i have an SQL datebase that is used for logging employees leave. we have some many different shifts, that on our employees table we have 7 fields that represent the days they work. these are a bit data type, 1 for working that day, and 0 for not working.
a second table has all the employees leave. containing employee id, leave date and reason.
i can easily query the employees table and get how many people are to work on any given day of the week, and i can easily query the leave table to see how many people are off on a given date.
what i looking to do is based on the day of the week in the leave table, count how many people are supposed to be in on that day.
the code im trying to make work is
select TBL_Leave.Leave_Date AS 'Date',
datepart(weekday,TBL_Leave.Leave_Date) - 1 AS 'Day Of Week',
count(TBL_Leave.Leave_Date) AS 'Total Off',
case
when datepart(weekday,TBL_Leave.Leave_Date) - 1 = 5 then select SUM(convert(int,Mon)) from TBL_Employees)
else 'Flase'
end
from TBL_Leave
where Leave_Date between '2010-01-01' AND '2010-12-31'
group by TBL_Leave.Leave_Date
but sure enough, it dont work.
im trying to count the number of people working from one table based the the day of the week from a field in another.
any help anyone can give will be great
cheers
Paul
i have this query to get how many people are off on any date
select TBL_Leave.Leave_Date AS 'Date',
datepart(weekday,TBL_Leave.Leave_Date) - 1 AS 'Day Of Week',
count(TBL_Leave.Leave_Date) AS 'Total Off'
from TBL_Leave
where Leave_Date between '2010-01-01' AND '2010-12-31'
group by TBL_Leave.Leave_Date
and this to see how many people are in on any day
select SUM(convert(int,Mon)) as 'Monday',
SUM(convert(int,Tue)) AS 'Tuesday',
SUM(convert(int,Wed)) AS 'Wednesday',
SUM(convert(int,Thu)) AS 'Thursday',
SUM(convert(int,Fri)) AS 'Friday',
SUM(convert(int,Sat)) AS 'Saturday',
SUM(convert(int,Sun)) AS 'Sunday'
from TBL_Employees
where planned = 1
IMHO you should set a view in place as a helper for queries like these:
create view V_EmployeeWorkingDays as
select EmployeeID,
case ShortDayName
when 'Mon' then 1 when 'Tue' then 2 when 'Wed' then 3
when 'Thu' then 4 when 'Fri' then 5 when 'Sat' then 6
when 'Sun' then 7 end as weekday,
IsWorking
from TBL_Employees
unpivot (IstWorking for ShortDayName in (Mon,Tue,Wed,Thu,Fri,Sat,Sun)) p;
Secondly you need the calendar dates within your range. You could use a function like this:
create function F_DateValues(#FromDate datetime, #ToDate datetime)
returns table as
return (
select dateadd(day,Nr-1,#FromDate) as Date
from (select row_number() over (rand()) as Nr
from (values (1),(1),(1),(1)) a
cross join (values (1),(1),(1),(1)) b
cross join (values (1),(1),(1),(1)) c
cross join (values (1),(1),(1),(1)) c) n
where Nr > datediff(day,#FromDate,#ToDate)
);
Now you can put this alltogether:
select d.Date,
isnull(w.CountWorkingPlanned,0)-isnull(l.CountLeaves,0) as CountWorking
from F_DateValue('20101118','20101128') d
left join (select LeaveDate, count(*) as CountLeaves
from TBL_LeaveDate group by LeaveDate) l
on l.LeaveDate = d.Date
left join (select weekday, count(*) as CountWorkingPlanned
from V_EmployeeWorkingDays where IsWorking=1 group by weekday) w
on w.weekday = datepart(weekday,d.Date);
This should be working (not tested - so please don't kill me for typos ;) ).
You should redesign the table layout. As you have a field for each weekday, that means that you have data in the field names. Data belongs inside the table, so you should put that data as rows in a separate table.
Then it's easy to get the data. Example:
select count(*)
from Employees e
left join Leave l on l.EmployeeId = e.EmployeeId and LeaveDate = #Today
left join Workdays w on w.EmployeeId = e.EmployeeId and w.WeekDay = datepart(weekday, #Today)
where l..EmployeeId is null and w.EmployeeId is null
SELECT count(id) FROM employee WHERE monday = true
Seems easy enough unless I still don't get what you need...
Here's a query that might work for you.
The query uses derived queries to get the leave and work counts. I included an UNPIVOT operation on the TBL_Employee data to make it easier to get the employee data. You can avoid this with design changes that have been suggested.
SELECT Leave.Leave_Date, WorkCount, LeaveCount,
WorkCount-LeaveCount AS CountDifference
FROM
(
-- Get Leave counts by date
SELECT Leave_Date, UPPER(LEFT(DATENAME(dw, Leave_Date), 3)) AS WorkDay,
COUNT(*) as LeaveCount
FROM TBL_Leave
WHERE Leave_Date between '2010-01-01' AND '2010-12-31'
GROUP BY Leave_Date, UPPER(LEFT(DATENAME(dw, Leave_Date), 3))
) AS Leave
LEFT OUTER JOIN
(
-- Get Work counts by day of week
SELECT WorkDay, COUNT(*) WorkCount
FROM
(
SELECT EmpID, Mon, Tue, Wed, Thu, Fri, Sat, Sun
FROM TBL_Employees
) p
UNPIVOT
(IsWorking FOR WorkDay IN
(Mon, Tue, Wed, Thu, Fri, Sat, Sun)
)AS unpvt
WHERE unpvt.IsWorking = 1
GROUP BY WorkDay
) AS Work ON Leave.WorkDay = Work.WorkDay -- Join on day of week
thanks for everyones help on this, i have picked up a few tips. i managed to get this sorted last night and when i look at it, i think i made it sound more complicated than it is. here is what i came up with.
create table TEMP_planned (id int null, mon int null, tue int null, wed int null, thur int null, fri int null, sat int null, sun int null)
insert into TEMP_planned (id, mon, tue, wed, thur, fri, sat, sun)
values(1,
(select SUM(convert(int,Mon)) from TBL_Employees where Planned = 1),
(select SUM(convert(int,Tue)) from TBL_Employees where Planned = 1),
(select SUM(convert(int,Wed)) from TBL_Employees where Planned = 1),
(select SUM(convert(int,Thu)) from TBL_Employees where Planned = 1),
(select SUM(convert(int,Fri)) from TBL_Employees where Planned = 1),
(select SUM(convert(int,Sat)) from TBL_Employees where Planned = 1),
(select SUM(convert(int,Sun)) from TBL_Employees where Planned = 1))
select TBL_Leave.Leave_Date,
'Planned' = case DATEPART(dw,TBL_Leave.Leave_Date) - 1
when 1 then (select mon from TEMP_Planned where ID = 1)
when 2 then (select tue from TEMP_Planned where ID = 1)
when 3 then (select wed from TEMP_Planned where ID = 1)
when 4 then (select thur from TEMP_Planned where ID = 1)
when 5 then (select fri from TEMP_Planned where ID = 1)
when 6 then (select sat from TEMP_Planned where ID = 1)
when 7 then (select sun from TEMP_Planned where ID = 1)
end,
COUNT(tbl_leave.Leave_Date) as 'Total Staff Off'
from TBL_Leave
group by TBL_Leave.Leave_Date
drop table temp_planned