getting results from date ranges for query mssql - sql

i have a query that returns the following,
Employee : AA AA
Manager : BB BB
Dates : Jan 26 2022 8:00AM - Feb 2 2022 5:00PM
Days Requested : 6
Type Of Leave : Annual Leave
Department : Corporate Accounting & Tax Services
what i want to do to get a result for the days ( i am trying to create a pivot table in excel from the data ) that contains all the dates in between for example
Employee : AA AA
Manager : BB BB
Dates : Jan 26 2022 8:00AM
Days Requested : 6
Type Of Leave : Annual Leave
Department : Corporate Accounting & Tax Services
Employee : AA AA
Manager : BB BB
Dates : Jan 27 2022
Days Requested : 6
Type Of Leave : Annual Leave
Department : Corporate Accounting & Tax Services
Employee : AA AA
Manager : BB BB
Dates : Jan 28 2022
Days Requested : 6
Type Of Leave : Annual Leave
Department : Corporate Accounting & Tax Services
until the end and im stuck.
any help would be appreciated
;WITH cte AS(
SELECT
MYUSER.firstname AS Firstname,
MYUSER.lastname AS Lastname,
LEAVES.date_start,
LEAVES.date_end,
LEAVES.leave_days_requested AS DaysRequested,
LEAVES.status As Status,
TYPESLEAVES.types_ofLeaves,
Manager.user_id AS managerId,
tbl_department.name_department
FROM tbl_leaves AS LEAVES
LEFT OUTER JOIN tbl_user AS MYUSER ON MYUSER.id = LEAVES.tbl_user_id
LEFT OUTER JOIN tbl_types_of_leaves AS TYPESLEAVES ON LEAVES.tbl_type_of_leave = TYPESLEAVES.id
LEFT OUTER JOIN tbl_manager_user AS ManagerUser ON ManagerUser.tbl_user_id = MYUSER.id
LEFT OUTER JOIN tbl_manager AS Manager ON ManagerUser.tbl_manager_id = Manager.id
INNER JOIN tbl_department ON tbl_department.id = MYUSER.department_id
WHERE LEAVES.status = 'Pending')
Select
CONCAT(a.Firstname,' ',a.Lastname) AS Employee,
LTRIM(RTRIM(CONCAT(m.firstname, ' ', m.lastname))) AS Manager,
a.date_start,
a.date_end,
a.DaysRequested AS 'Days Requested',
a.types_ofLeaves AS 'Type Of Leave',
a.name_department AS 'Department'
FROM cte a
LEFT OUTER JOIN tbl_user m ON m.id = a.managerId

Thank you for your reply i created a date table indeed and joined it together and worked like a charm thxx
INNER JOIN tbl_leaves_dates d
on d.date >= a.date_start
and d.date <= a.date_end

Related

SQL query to find the faculty which have taught every subject

I need to write a SQL query to find the faculty which has taught every subject (ie Sam)
With nested queries
Without using aggregate functions (no count, avg, min etc).
I can't seem to figure this out, would really appreciate some help =)
Faculty
fid
fname
fqualifications
fexperience
salary
deptname
100
Sam
ME CS
10
100000
IT
101
John
ME IT
8
80000
IT
102
Max
ME CS
9
90000
CS
103
Jenny
ME CS
5
50000
CS
Course
cid
cname
semester
1
SE
4
2
WT
4
3
CG
5
4
DBMS
5
Teaches
fid
cid
year
100
1
2019
100
2
2018
100
3
2020
100
4
2021
101
1
2017
101
2
2018
102
2
2018
102
3
2019
103
3
2020
103
4
2021
I used this query to find the output but according to the question I can't.
select * from faculty f
-> inner join teaches t
-> on f.fid=t.fid
-> inner join course c
-> on t.cid=c.cid
-> group by f.fid,f.fname
-> having count(*)=4;
OUTPUT:
fid
fname
fqualifications
fexperience
salary
deptname
fid
cid
year
cid
cname
semester
100
Sam
ME CS
10
100000
IT
100
1
2019
1
SE
4
Not the most efficient way to proceed, but with the requirements given to you, I would try and rephrase the query like this:
"A faculty that has taught every subject is a faculty that has not skipped even one subject".
Now, faculties that have skipped a subject will have a NULL when LEFT JOINed with the syllabus and all the subjects. Pseudo-SQL:
SELECT DISTINCT faculty.id FROM faculties
LEFT JOIN has_taught ON (has_taught.faculty_id = faculty.id)
LEFT JOIN subjects ON (has_taught.subject_id = subjects.id)
WHERE has_taught.faculty_id IS NULL;
or in some databases you maybe need
SELECT DISTINCT faculty.id FROM faculties
CROSS JOIN subjects
LEFT JOIN has_taught ON
(has_taught.faculty_id = faculty.id AND has_taught.subject_id = subjects.id)
WHERE has_taught.faculty_id IS NULL;
So, faculties that are NOT IN this list would naturally be
SELECT * FROM faculties
WHERE faculty.id NOT IN (
SELECT DISTINCT faculty.id ...
);
and this should only use nested queries, as requested.
Or with a further join
SELECT faculties.* FROM faculties
LEFT JOIN (
SELECT DISTINCT faculty.id ...
) AS they_skipped_some
ON (they_skipped_some.id = faculties.id)
WHERE they_skipped_some.id IS NULL

How to perform group function over an outer join query?

I have the following categories:
category_id name
----- -----
50D34E5A-A935-490A-9492-153DE50A94A2 Luxuries
013E3D0F-E755-495B-8D1E-4A3D1340ACF8 Household
88C477EE-CF99-49B4-9E92-4C41B09A5715 Petrol
40099E3A-18F1-4710-A803-7107648518CC Other
E3B81693-07B5-4D69-A3EC-796CA4290B45 Rent
F0728052-0733-454B-B8EE-96AB6D6E40BE Insurance
6E06581A-1643-4DEC-90B7-9D57F770F313 Groceries
CFD1ED67-7059-4A33-8DD6-F2FFAB213970 Monthly Bill
And the following transactions (shortened and joined on category_id):
category_id amount
------ -----
Luxuries 14
Household 14
Petrol 14
Other 14
Rent 14
Insurance 14
There are no Groceries transactions. I would like to sum these amounts and display their count but include Groceries in the results, but displaying zero. I have tried this:
SELECT SUM(ut.amount), COUNT(ut.amount), c.name
FROM User_Transaction ut
FULL OUTER JOIN Category c ON (ut.category_id = c.category_id)
GROUP BY c.name
total count name
--- --- ---
84 6 Household
84 6 Insurance
84 6 Luxuries
98 7 Monthly Bill
56 4 Other
182 13 Petrol
112 8 Rent
But Groceries has not been included. How can I include Groceries on the result set but just displaying as 0?
Use a LEFT JOIN starting with category (that values you want to keep):
SELECT c.name, COALESCE(SUM(ut.amount), 0) as amount,
COUNT(ut.category_id) as num_transactions,
FROM Category c LEFT JOIN
User_Transaction ut
ON ut.category_id = c.category_id
GROUP BY c.category_id, c.name;
That said, I think your query should do what you want, although it is misleading to use a full join in this context.

New to SQL - How to compare data from two sets of joined tables

I'm trying to compare a set of multiple tables against another set of multiple tables in a SQL database. Admittedly, I'm very novice to SQL so please forgive me if my terminology is incorrect.
I have 6 individual tables in my database. 3 of those are comprised of current month's data and the other three are prior month's data. I need to produce a report that shows current month data, but also compare the account balance against the prior month - I need to create a column that will list "true" or "false" based on whether the account balances match.
I have joined the three current month's data tables together and I have joined the three prior month's data tables together.
The two sets of tables are identical. Below is a description of the tables - There is one set prefixed "CURRENT" and one prefixed "PRIOR":
BALANCE:
EntityID
AccountID
AccountBalance
ENTITY:
ID
Label
Description
ACCOUNT:
ID
AccountNumber
Description
The report I need to provide should list the following from the current month's data:
Label
Description
AccountNumber
AccountDescription
AccountBalance
I need to add a column called "Changed" at the end of the report. This column should have a "True" or "False" value depending on whether or not the current & prior account balances match.
Thus far, I have only been able to join the tables. I'm unsure how to edit this query to compare the current month dbo.CURRENT_BALANCE.AccountBalance against the prior month's dbo.PRIOR_BALANCE.AccountBalance
SELECT DISTINCT
dbo.CURRENT_ENTITY.Label,
dbo.CURRENT_ENTITY.Description AS Entity,
dbo.CURRENT_ACCOUNT.AccountNumber,
dbo.CURRENT_ACCOUNT.Description AS AccountDescription,
dbo.CURRENT_BALANCE.GLAccountBalance
FROM
dbo.CURRENT_BALANCE
INNER JOIN dbo.CURRENT_ENTITY ON dbo.CURRENT_BALANCE.EntityID = dbo.CURRENT_ENTITY.ID
INNER JOIN dbo.CURRENT_ACCOUNT ON dbo.CURRENT_BALANCE.AccountID = dbo.CURRENT_ACCOUNT.ID
CROSS JOIN dbo.PRIOR_BALANCE
INNER JOIN dbo.PRIOR_ENTITY ON dbo.PRIOR_BALANCE.EntityID = dbo.PRIOR_ENTITY.ID
INNER JOIN dbo.PRIOR_ACCOUNT ON dbo.PRIOR_BALANCE.AccountID = dbo.PRIOR_ACCOUNT.ID
The query above returns my expected results:
Label Entity AccountNumber AccountDescription AccountBalance
21 Company ABC 1 Customer Sales 25
21 Company ABC 2 Customer Sales 568
22 XYZ Solutions 3 Vendor Sales 344
23 Number 1 Products 4 Vendor Sales 565
24 Enterprise Inc 5 Wholesale 334
24 Enterprise Inc 6 Wholesale 5452
24 Enterprise Inc 7 Wholesale 5877
26 QWERTY Solutions 8 Customer Sales 456
27 Acme 9 Customer Sales 752
28 United Product Solutions 10 Vendor Sales 87
What I would like to do is have a result similar to:
Label Entity AccountNumber AccountDescription AccountBalance Changed
21 Company ABC 1 Customer Sales 25 FALSE
21 Company ABC 2 Customer Sales 568 FALSE
22 XYZ Solutions 3 Vendor Sales 344 FALSE
23 Number 1 Products 4 Vendor Sales 565 FALSE
24 Enterprise Inc 5 Wholesale 334 TRUE
24 Enterprise Inc 6 Wholesale 5452 FALSE
24 Enterprise Inc 7 Wholesale 5877 TRUE
26 QWERTY Solutions 8 Customer Sales 456 FALSE
27 Acme 9 Customer Sales 752 FALSE
28 United Product Solutions 10 Vendor Sales 87 FALSE
I have no idea where to go from here. Would appreciate any advise from this group!
The below should work as a way to compare the 2 values.
I have added aliases to table names to help with reading;
SELECT DISTINCT
ce.Label
,ce.Description AS Entity
,ca.AccountNumber
,ca.Description AS AccountDescription
,cb.GLAccountBalance
,CASE
WHEN cb.GLAccountBalance = p.PriorBalance THEN 'False'
WHEN cb.GLAccountBalance <> p.PriorBalance THEN 'True'
END AS [Changed]
FROM dbo.CURRENT_BALANCE cb
INNER JOIN dbo.CURRENT_ENTITY ce ON cb.EntityID = ce.ID
INNER JOIN dbo.CURRENT_ACCOUNT ca ON cb.AccountID = ca.ID
LEFT JOIN ( SELECT DISTINCT
pe.ID AS PE_ID
,pa.ID AS PA_ID
,pb.GLAccountBalance AS PriorBalance
FROM dbo.PRIOR_BALANCE pb
INNER JOIN dbo.PRIOR_ENTITY pe ON pb.EntityID = pe.ID
INNER JOIN dbo.PRIOR_ACCOUNT pa ON pb.AccountID = pa.ID
) p ON p.PE_ID = ce.ID AND p.PA_ID = ca.ID

insert duplicate rows in temp table

i'm a new to sql & forum - need help on how to insert duplicate rows in temp table. Would like to create a view as result
View - Employee:
Name Empid Status Manager Dept StartDate EndDate
AAA 111 Active A111 Cashier 2015-01-01 2015-05-01
AAA 111 Active A222 Sales 2015-05-01 NULL
I don't know how to write a function, but do have a DATE table.
Date Table: (365 days) goes up to 2018
Date Fiscal_Wk Fiscal_Mon Fiscal_Yr
2015-01-01 1 1 2015
Result inquiry
How do i duplicate rows for each record from Employee base on each of the start date for entire calendar year.
Result:
Name Empid Status Manager Dept Date FW FM FY
AAA 111 Active A111 Cashier 2015-01-01 1 1 2015
AAA 111 Active A111 Cashier 2015-01-02 1 1 2015
******so on!!!!!!
AAA 111 Active A222 Sales 2015-05-01 18 5 2015
AAA 111 Active A222 Sales 2015-05-02 18 5 2015
******so on!!!!!!
Thanks in advance,
Quinn
Select * from Employee cross join Calendar.
This will essentially join every record in calendar to every record in Employee.
so, if there are 2 records in Employee and 10 in calendar, you'll end up with 20 total, 10 for each.
What you are looking for is a join operation. However, the condition for the join is not equality, because you want all rows that match between two values.
The basic idea is:
select e.*, c.date
from employee e join
calendar c
on e.startdate >= c.date and
(e.enddate is null or c.date <= e.enddate);
modified query - this yields result of previous & most recent records
select e.*, c.date, c.FW, c.FM, c.FY
from employee e
join calendar c
on e.startdate <= c.date and
ISNULL(e.enddate,GETDATE()) > c.date

Group Join between three tables to get the percentage

I have three tables Attendance, Employee, Sector
Employee Table
EmiId -Name -SectorId
123 ABC 1
231 BCD 2
125 WER 1
Attendance
AttId -EmpId -Dt
1 123 12/12/2014 9:00
2 231 12/12/2014 10:00
Sector
SectorId -SectorName
1 North Sector
2 East Sector
my query is
SELECT COUNT(Attendance.Emp_Id) as AttCount,(select COUNT(*) from Employee) as EmpCount
FROM Employee INNER JOIN
Sector ON Employee.SectorId = Sector.SectorId INNER JOIN
Attendance ON Employee.EmpId = Attendance.EmpId
group by Sector.SectorId
and i keep getting same number of employees for both instead so the (select COUNT(*) from Employee)- EmpCount seems to be incorrect.I keep getting the same number for both the sectors. Although the Attcount seems to work fine.
Please help. Thanks in advance.
You just making select count from the same table - do not expect other results.
Perhaps someone could do it better
SELECT COUNT(Attendance.Emp_Id),COUNT(case when Employee.empid=attendance.attid then 1 else 0 end)
FROM Employee JOIN Sector ON Employee.SectorId = Sector.SectorId
LEFT JOIN Attendance ON Employee.EmpId = Attendance.Emp_Id
group by Sector.SectorId
Maybe you need LEFT JOIN with Attendance
SELECT COUNT(Attendance.Emp_Id),(select COUNT(*) from Employee)
FROM Employee JOIN Sector ON Employee.SectorId = Sector.SectorId
LEFT JOIN Attendance ON Employee.EmpId = Attendance.EmpId
group by Sector.SectorId