SQL Server - How to remove repeating 2nd column - sql-server

I have query that is similar to the following and wish to remove the repeating rows in the second/third column...need examples where I can use the following (top 1, max, min, etc...) or other best method without using derived query to remove the duplicate values. Thanks JK
WITH cteEMPAssistants (executive_personnel_number, assistant_personnel_number, assistant_type, SecType) AS
(SELECT DISTINCT CASE
WHEN ISNUMERIC(KA.KIT_asgn_emplid) = 1 THEN CAST(CAST(KA.KIT_asgn_emplid AS INT) AS VARCHAR(11))
ELSE ''
END AS executive_personnel_number ,
CAST(CAST(KAP.emplid AS INT) AS VARCHAR(11)) AS assistant_personnel_number ,
ISNULL(LATT1.xlatlongname, '') AS assistant_type ,
CAST(LATT1.fieldvalue AS VARCHAR(4)) AS SecType ,
ISNULL(LATT3.xlatshortname, '') AS assign_role
FROM dbo.KIT_ASGN_PRNT AS KAP
LEFT OUTER JOIN dbo.KIT_ASSIGNMENTS AS KA ON KA.emplid = KAP.emplid
AND KA.effdt = KAP.effdt
LEFT OUTER JOIN dbo.KIT_EMPLOYEES AS EXECT ON EXECT.EMPLID = KA.KIT_ASGN_EMPLID
LEFT OUTER JOIN dbo.KIT_EMPLOYEES AS ASST ON ASST.EMPLID = KAP.EMPLID
LEFT OUTER JOIN dbo.XLATITEM AS LATT1 ON LATT1.fieldname = 'KIT_ASGN_TYPE'
AND LATT1.fieldvalue = KAP.KIT_asgn_type
LEFT OUTER JOIN dbo.XLATITEM AS LATT3 ON LATT3.fieldname = 'KIT_ASGN_ROLE'
AND LATT3.fieldvalue = KA.KIT_asgn_role
AND LATT3.xlatshortname = 'Primary'
WHERE KAP.effdt =
(SELECT MAX(effdt)
FROM dbo.KIT_ASGN_PRNT
WHERE emplid = KAP.emplid
AND effdt <= GETDATE() ) --Return data only when employee and assistant active; null is for temps
AND (EXECT.EMP_STATUS = 'A'
OR EXECT.EMP_STATUS IS NULL )
AND ASST.EMP_STATUS = 'A' --Return all floating secretaries
AND (KAP.KIT_asgn_type = 'F' --Return all assigned secretaries, who are assigned to a person and not a task
OR (KAP.KIT_asgn_type IN ('A',
'AF')
AND KA.KIT_asgn_person = 'Y' ) ) )
SELECT CAST(EMP.KIT_EMPLID AS VARCHAR(15)) AS employeeNumber ,
KAP.emplid AS Assistant ,
SECRES.SecType AS SecType
FROM dbo.KIT_EMPLOYEES AS EMP
LEFT OUTER JOIN cteEMPAssistants AS SECRES ON EMP.KIT_EMPLID = SECRES.assistant_personnel_number
WHERE (EMP.EMP_STATUS = 'A')
AND (EMP.PER_ORG IN ('EMP',
'CWR'))
AND (ISNULL(EMP.KIT_NETWORK_ID, '') <> '')
Here is sample output:
employeeNumber Assistant SecType
--------------- --------- -----------------
1234 1112 A
1234 1112 A
1234 1112 A
1234 1112 A
4567 1113 NULL
1278 1114 NULL
1365 1115 NULL
1298 1116 A
1476 1117 A
1191 1118 NULL

You should be able to append this to the end of your query:
GROUP BY EMP.KIT_EMPLID, KAP.emplid, SECRES.SecType

Related

Find loops within data using SQL Server

I have the following data to find the loop.
Table:
CREATE TABLE tblLoop
(
person1 varchar(20),
person2 varchar(20)
);
INSERT INTO tblLoop VALUES('A','B'),('A','C'),('A','D'),
('B','E'),('B','F'),
('D','G'),('D','H'),
('F','i'),
('G','J'),
('i','A'),
('J','D');
Edit: Added some more values
INSERT INTO tblLoop VALUES('X','Y'),('X','Z'),('Z','X'),('Y','W');
Records Look like:
Note: There is possibility of multiple trees like above we need to find all trees loop data.
Requirement: I need to find the persons which forms a loop. For an example in the given data we found 2 Loop's:
Loop 1: A connected with B connected with F connected with i connected with A.
Loop 2: A connected with D connected with G connected with J connected with D.
Expected result:
LoopFound
--------------------
A->B->F->i->A
A->D->G->J->D
X->Z->X
My try:
;WITH CTE_Loop AS
(
SELECT t.Person1,t.Person2,
CONVERT(VARCHAR(500), t.Person1 + '->' + t.Person2) AS [Loop],
0 AS FoundFlag
FROM tblLoop t
UNION ALL
SELECT t.Person1,t.Person2,
CONVERT(VARCHAR(500), cte.[Loop] +'->'+t.Person2) AS [Loop],
CASE WHEN CHARINDEX(t.Person2, cte.[Loop]) != 0 THEN 1 ELSE 0 END AS FoundFlag
FROM CTE_Loop cte
INNER JOIN tblLoop t ON t.Person1 = cte.Person2
WHERE cte.FoundFlag = 0 AND t.Person1 <> '-' AND t.Person2 <> '-'
)
SELECT [Loop] AS LoopFound
FROM CTE_Loop
WHERE FoundFlag = 1
GROUP BY [Loop];
SELECT
CONCAT_WS('->',t1.person1,t1.person2,t2.person2 ,t3.person2,t4.person2)
FROM tblLoop t1
left join tblLoop t2 on t1.person2 = t2.person1
left join tblLoop t3 on t2.person2 = t3.person1
left join tblLoop t4 on t3.person2 = t4.person1
where t1.person1 = 'A'AND t4.person2 IS NOT NULL
You could get the start&end of the loops assuming a hierarchy of some sort(eg. A comes before B which is before C etc) and exclude rows whose person2 does not appear as person1 (i.e the ends of the relation/chain)...
--get loops
select distinct a.person1, b.person1, b.person2 --a.person1, b.person1 :: loop range(start-end)
from tblLoop as a
join tblLoop as b on a.person1 = b.person2 and a.person1 <= b.person1 --assume a hierarchy by name (A is on a higher/or equal level than B etc)
where exists(select * from tblLoop as d where d.person1 = a.person2) --exclude dead ends (person2 which is not person1);
..and inject that into the cte. You could work out overlaps and loops without the same start&end.
(for eg. A->D->G->J->D or D->G->J->D is a loop?)
;WITH CTE_Loop AS
(
SELECT t.Person1,t.Person2,
CONVERT(VARCHAR(500), t.Person1 + '->' + t.Person2) AS [Loop],
0 AS FoundFlag
FROM tblLoop t
where t.person1 in
(
select distinct a.person1--, b.person1, b.person2 --a.person1, b.person1 :: loop range(start-end)
from tblLoop as a
join tblLoop as b on a.person1 = b.person2 and a.person1 <= b.person1 --assume a hierarchy by name (A is on a higher/or equal level than B etc)
where exists(select * from tblLoop as d where d.person1 = a.person2) --exclude dead ends (person2 which is not person1)
)
UNION ALL
SELECT t.Person1,t.Person2,
CONVERT(VARCHAR(500), cte.[Loop] +'->'+t.Person2) AS [Loop],
CASE WHEN CHARINDEX(t.Person2, cte.[Loop]) != 0 THEN 1 ELSE 0 END AS FoundFlag
FROM CTE_Loop cte
INNER JOIN tblLoop t ON t.Person1 = cte.Person2
WHERE cte.FoundFlag = 0 AND t.Person1 <> '-' AND t.Person2 <> '-'
)
SELECT [Loop] AS LoopFound
FROM CTE_Loop
WHERE FoundFlag = 1
GROUP BY [Loop];

This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression in sql query

I know that this type of question is duplicate but I didnt find accurate answer of this problem. So thats why I post it.
So, my question is that when I am running the sql query in sql server at that time it shows the heading error. I find many of things but didnt work.
Here is my query,
select
trandate, shortdescr, ref as BillNo,
f.companyname, h.brnchname,
tranno, AccName,
sum(dramount) as NetAmount, sum(SGST) GstAmt,
sum(CGST) CstAmt, sum(IGST) IGstAmt, s.SeriesName
from
(select
trandate, shortdescr, ref, dramount, CompanyID,
brnchid, accountid, refaccountid, tranno, seriesid,
case
when accountid = (select top 1 gcsysdescription
from systemparameters
where gcsysvar = 'SGST')
then dramount - cramount
else 0
end as SGST,
case
when accountid = (select top 1 gcsysdescription
from systemparameters
where gcsysvar = 'CGST' )
then dramount - cramount
else 0
end as CGST,
case
when accountid = (select top 1 gcsysdescription
from systemparameters
where gcsysvar = 'IGST' )
then dramount - cramount
else 0
end as IGST,
case
when srno = 1 --=(select top 1 gcsysdescription from systemparameters where gcsysvar='IGST' )
then (select accmas.accountname
from accountdet accdet
left outer join accountmaster accmas on accmas.accountid = accdet.accountid
where accdet.srno = 1 and accdet.seriesid = 19)
end as AccName
from
accountdet) as abc
left outer join
companymaster F on abc.CompanyID = F.companyid
left outer join
brnchmst H on abc.brnchid = H.brnchid
left outer join
Accountmaster a on abc.accountid=a.accountid
left outer join
SeriesMaster s on abc.SeriesID=s.SeriesID
where
abc.companyid = 37
and abc.brnchid in (7, 9, 8, 3, 4)
and abc.seriesid = 19
and convert(varchar(10), trandate, 112) >= '20170920'
and convert(varchar(10), trandate, 112) <= '20180331'
and a.EntryType <> 'D'
and abc.dramount <> 0
group by
trandate, shortdescr, ref, f.companyname, h.brnchname, tranno, s.seriesname, AccName
Please help me to solve this issues.
Thank You.
It seems that your subquery
select accmas.accountname from accountdet accdet LEFT OUTER JOIN accountmaster accmas
ON accmas.accountid= accdet.accountid where accdet.srno = 1 and accdet.seriesid = 19
sometimes return more than one row. You should change predicates in where or add TOP(1)...ORDER BY.

how to check if password expiry column in a store procedure has only 14,7,3,2,1 days left?

i have an sp that i check if user's password change date has 14 days
left(flag=0) and i send email to that users and i that sp i check(by a
col.flag) if email already sent or not.after that i update the the
flag col.in an another SP(ExpiryNotificationFlag) to 1 of users list whose email has
already sent..now i don't know how to check for 7,3,2,1 days as flag
col value is already 1 ?
sp
SELECT TenantName
, TenantEmail
, GMAP_code
, ContactID FROM (
SELECT b_1.TenantName
, b_1.TenantEmail
, LastPDWChangeDate =(SELECT ISNULL(max (DateChanged),GETDATE()) FROM dbo.wsm_Contact_PwdHistory WHERE ContactID = b_1.TenantRegContactID)
, ExpiryNotificationFlag =(SELECT top 1 ExpiryNotificationFlag FROM dbo.wsm_Contact_PwdHistory WHERE ContactID = b_1.TenantRegContactID order by DateChanged desc)
, GMAP_code =(SELECT TOP 1 ISNULL(GMAP_CODE,'') from wsm_Ref_Buildings where BuildingId = b_1.BuildingID)
, b_1.TenantRegContactID as ContactID
FROM dbo.wsm_Contact AS a LEFT OUTER JOIN
(
SELECT C.Name AS TenantName
, A.SiteID
, A.BuildingID
, A.FloorID
, A.ContactID AS TenantRegContactID
, D.LEASID
, C.Phone AS TenantPhone
, C.Email AS TenantEmail
, B.UserID AS userid
, C.Mobile AS TenantMobile
, B.UserType
FROM dbo.wsm_Contact_Tenancy AS A
INNER JOIN dbo.wsm_Contact_User AS B ON A.ContactID = B.ContactID AND B.Active = 1
INNER JOIN dbo.wsm_Contact AS C ON B.ContactID = C.ContactID
INNER JOIN (
SELECT DISTINCT COALESCE (LEASID, ExtLeasNum) AS LEASID
, SiteID
, BuildingID
, FloorID
FROM dbo.wsm_Contact) AS D ON A.SiteID = D.SiteID AND A.BuildingID = D.BuildingID AND A.FloorID = D.FloorID) AS b_1 ON
COALESCE (a.LEASID, a.ExtLeasNum) = b_1.LEASID AND a.SiteID = b_1.SiteID AND a.BuildingID = b_1.BuildingID AND a.FloorID = b_1.FloorID
INNER JOIN dbo.wsm_Ref_Floors AS C ON a.FloorID = C.FloorId
WHERE (a.OCCPSTAT NOT IN ('I', 'P')) and C.Deleted = 0 and b_1.userid is not null ) AS A WHERE DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 76 AND ISNULL(ExpiryNotificationFlag,0) <> 1
END
update Query
UPDATE dbo.wsm_Contact_PwdHistory set ExpiryNotificationFlag = 1 WHERE ContactID = #ContactID
you can do it like that
( (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 76 AND ISNULL(ExpiryNotificationFlag,0) = 0) --14 days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 83 AND ISNULL(ExpiryNotificationFlag,0) = 1) --7days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 87 AND ISNULL(ExpiryNotificationFlag,0) = 2) --3 days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 88 AND ISNULL(ExpiryNotificationFlag,0) = 3) --2 days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 89 AND ISNULL(ExpiryNotificationFlag,0) = 4) --1 day
)
for that u have to modify Expiry notification flag to int instead of a Boolean
after that make a SP where will u update the value from
0 to 1,1 to 2,2 to 3 etc.
Youre essentially making the following complaint:
"A boolean datatype can only store one of two values!"
Indeed, so swap out that flag for a "Number of Days Left" column, and compare it to 14, 7, whatever....
Note, ExpiryNotificationFlag column isn't a great name - how about "PasswordExpiryEmailSent"
Sometimes these problems get a lot easier to think about when the columns have better names

joining on count and rank the result t sql

Here's my Count_query:
Declare #yes_count decimal;
Declare #no_count decimal;
set #yes_count=(Select count(*) from Master_Data where Received_Data='Yes');
set #no_count=(Select count(*) from Master_Data where Received_Data='No');
select #yes_count As Yes_Count,#no_count as No_Count,(#yes_count/(#yes_count+#no_count)) As Submission_Count
I am having trouble making joins on these two queries
This is the rest of the query:
Select Distinct D.Member_Id,d.Name,d.Region_Name, D.Domain,e.Goal_Abbreviation,
e.Received_Data, case when Received_Data = 'Service Not Provided' then null
when Received_Data = 'No' then null else e.Improvement end as
Percent_Improvement , case when Received_Data = 'Service Not Provided' then null
when Received_Data = 'No' then null else e.Met_40_20 end as Met_40_20
FROM (
select distinct member_Domains.*,
(case when NoData.Member_Id is null then 'Participating' else ' ' end) as Participating
from
(
select distinct members.Member_Id, members.Name, Members.Region_Name,
case when Domains.Goal_Abbreviation = 'EED Reduction' then 'EED'
When Domains.Goal_Abbreviation = 'Pressure Ulcers' then 'PRU'
when Domains.Goal_Abbreviation = 'Readmissions' then 'READ' else Domains.Goal_Abbreviation end as Domain from
(select g.* from Program_Structure as ps inner join Goal as g on ps.Goal_Id = g.Goal_Id
and ps.Parent_Goal_ID = 0) as Domains
cross join
(select distinct hc.Member_ID, hc.Name,hc.Region_Name from zsheet as z
inner join Hospital_Customers$ as hc on z.CCN = hc.Mcare_Id) as Members
) as member_Domains
left outer join Z_Values_Hospitals as NoData on member_Domains.member_ID = NoData.Member_Id
and Member_Domains.Domain = noData.ReportName) D
Left Outer JOIN
(SELECT B.Member_ID, B.Goal_Abbreviation, B.minRate, C.maxRate, B.BLine, C.Curr_Quarter, B.S_Domain,
(CASE WHEN B.Member_ID IN
(SELECT member_id
FROM Null_Report
WHERE ReportName = B.S_Domain) THEN 'Service Not Provided' WHEN Curr_Quarter = 240 THEN 'Yes' ELSE 'No' END) AS Received_Data,
ROUND((CASE WHEN minRate = 0 AND maxRate = 0 THEN 0 WHEN minRate = 0 AND maxRate > 0 THEN 1 ELSE (((maxRate - minRate) / minRate) * 100) END), .2) AS Improvement,
(CASE WHEN ((CASE WHEN minRate = 0 AND maxRate = 0 THEN 0 WHEN minRate = 0 AND maxRate > 0 THEN 1 ELSE (maxRate - minRate) / minRate END)) <= - 0.4 OR
maxRate = 0 THEN 'Yes' WHEN ((CASE WHEN minRate = 0 AND maxRate = 0 THEN 0 WHEN minRate = 0 AND maxRate > 0 THEN 1 ELSE (maxRate - minRate) / minRate END))
<= - 0.2 OR maxRate = 0 THEN 'Yes' ELSE 'No' END) AS Met_40_20
FROM (SELECT tab.Member_ID, tab.Measure_Value AS minRate, tab.Goal_Abbreviation, A.BLine, tab.S_Domain
FROM Measure_Table_Description AS tab INNER JOIN
(SELECT DISTINCT
Member_ID AS new_memid, Goal_Abbreviation AS new_measure, MIN(Reporting_Period_ID) AS BLine, MAX(Reporting_Period_ID)
AS Curr_Quarter
FROM Measure_Table_Description
WHERE (Member_ID > 1) AND (Measure_Value IS NOT NULL) AND (Measure_ID LIKE '%O%')
GROUP BY Goal_Abbreviation, Member_ID) AS A ON tab.Member_ID = A.new_memid AND tab.Reporting_Period_ID = A.BLine AND
tab.Goal_Abbreviation = A.new_measure) AS B FULL OUTER JOIN
(SELECT tab.Member_ID, tab.Measure_Value AS maxRate, tab.Goal_Abbreviation, A_1.Curr_Quarter
FROM Measure_Table_Description AS tab INNER JOIN
(SELECT DISTINCT
Member_ID AS new_memid, Goal_Abbreviation AS new_measure,
MIN(Reporting_Period_ID) AS BLine, MAX(Reporting_Period_ID)
AS Curr_Quarter
FROM Measure_Table_Description AS Measure_Table_Description_1
WHERE (Member_ID >1) AND (Measure_Value IS NOT NULL) AND (Measure_ID LIKE '%O%')
GROUP BY Goal_Abbreviation, Member_ID) AS A_1 ON tab.Member_ID = A_1.new_memid
AND tab.Reporting_Period_ID = A_1.Curr_Quarter AND
tab.Goal_Abbreviation = A_1.new_measure) AS C ON B.Member_ID = C.Member_ID
WHERE (B.Goal_Abbreviation = C.Goal_Abbreviation) ) E ON D.Member_Id = E.Member_ID AND d.Domain = E.S_Domain
ORDER BY D.Domain,D.Member_ID
How do I get a count of the 'yes'/ (count(yes)+count(no)) for each member_ID as column1 and also display the rank of each member_ID against all the member_IDs in the result as column2. I have come up with a query that generates the count for the entire table, but how do I restrict it each Member_ID.
Thanks for your help.
I haven't taken the time to digest your provided query, but if abstracted to the concept of having an aggregate over a range of data repeated on each row, you should look at using windowing functions. There are other methods, such as using a CTE to do your aggregation and then JOINing back to your detailed data. That might work better for more complex calculations, but the window functions are arguably the more elegant option.
DECLARE #MasterData AS TABLE
(
MemberID varchar(50),
MemberAnswer int
);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 0);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jane', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jane', 0);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jane', 1);
-- Method 1, using windowing functions (preferred for performance and syntactical compactness)
SELECT
MemberID,
MemberAnswer,
CONVERT(numeric(19,4),SUM(MemberAnswer) OVER (PARTITION BY MemberID)) / CONVERT(numeric(19,4),COUNT(MemberAnswer) OVER (PARTITION BY MemberID)) AS PercentYes
FROM #MasterData;
-- Method 2, using a CTE
WITH MemberSummary AS
(
SELECT
MemberID,
SUM(MemberAnswer) AS MemberYes,
COUNT(MemberAnswer) AS MemberTotal
FROM #MasterData
GROUP BY MemberID
)
SELECT
md.MemberID,
md.MemberAnswer,
CONVERT(numeric(19,4),MemberYes) / CONVERT(numeric(19,4),MemberTotal) AS PercentYes
FROM #MasterData md
JOIN MemberSummary ms
ON md.MemberID = ms.MemberID;
First thought is: your query is much, much too complicated. I have spent about 10 minutes now trying to make sense of it and haven't gotten anywhere, so it's obviously going to pose a long-term maintenance challenge to those within your organization going forward as well. I would really recommend you try to find some way of simplifying it.
That said, here is a simplified, general example of how to query on a calculated value and rank the results:
CREATE TABLE member (member_id INT PRIMARY KEY);
CREATE TABLE master_data (
transaction_id INT PRIMARY KEY,
member_id INT FOREIGN KEY REFERENCES member(member_id),
received_data BIT
);
-- INSERT data here
; WITH member_data_counts AS (
SELECT
m.member_id,
(SELECT COUNT(*) FROM master_data d WHERE d.member_id = m.member_id AND d.received_data = 1) num_yes,
(SELECT COUNT(*) FROM master_data d WHERE d.member_id = m.member_id AND d.received_data = 0) num_no
FROM member m
), member_data_calc AS (
SELECT
*,
CASE
WHEN (num_yes + num_no) = 0 THEN NULL -- avoid division-by-zero error
ELSE num_yes / (num_yes + num_no)
END pct_yes
FROM member_data_counts
), member_data_rank AS (
SELECT *, RANK() OVER (ORDER BY pct_yes DESC) AS RankValue
FROM member_data_calc
)
SELECT *
FROM member_data_rank
ORDER BY RankValue ASC;

To find percentage compliance using T-SQL

I'm not an expert in T-SQL so here I'm trying to find the % compliance for flu vaccine ,TB test and resiprator test by supervisor for medical staffs. Each employee has a supervisor name linked to their employee info. The below code works fine and it's giving me the % for the above tests. The problem is that I want to get the ID, Name and Department by Supervisor and the % compliance.
The expected output is like this:
Supervisor ID NAME Dept %Flu %TB %FIT
Elaine Jong 98% 100% 52%
001 MARY SURGERY
002 SUSAN SURGERY
James Ande 100% 98% 78%
267 JIM INPATIENT
789 SAM INPATIENT
Current OUTPUT
%Flu %TB %FIT
Elaine Jong 98% 100% 52%
James Ande 100% 98% 78%
And the Query:
SELECT E.FLDSUPRNAME AS Supervisor,
1.0*SUM(
CASE WHEN I.FLDDATE IS NULL
THEN 0 ELSE 1
END)/SUM(1) AS Percent_Flu_Compliant,
1.0*SUM(
CASE WHEN F.FLDDATE IS NULL OR (F.FLDDATE+365) < GETDATE()
THEN 0 ELSE 1
END) / SUM(1)
AS Percent_Fit_Compliant,
1.0*SUM(
CASE WHEN PPDx.FLDDATEDUE IS NULL
AND TBSSx.FLDDATEDUE IS NULL
AND CDUEx.FLDDATEDUE IS NULL
THEN 1 ELSE 0
END) /SUM(1) AS Percent_TB_Compliant
FROM EMPLOYEE E
LEFT OUTER JOIN DEPT D
ON D.FLDCODE= E.FLDDEPT
LEFT OUTER JOIN IMMUNE I ON I.FLDEMPLOYEE = E.FLDREC_NUM AND I.FLDTYPE IN ('109', '111')
AND I.FLDDATE = ( SELECT MAX(FLDDATE) FROM IMMUNE I2 WHERE E.FLDREC_NUM = I2.FLDEMPLOYEE
AND I2.FLDTYPE IN ('109','111') ) AND I.FLDDATE >= #Flu_Date AND I.FLDDATE <= GETDATE()
LEFT OUTER JOIN FITTEST F ON E.FLDREC_NUM = F.FLDEMPLOYEE
AND F.FLDDATE = (SELECT MAX(FLDDATE) FROM FITTEST F2 WHERE E.FLDREC_NUM = F2.FLDEMPLOYEE)
LEFT OUTER JOIN REQEXAM PPDx
ON PPDx.FLDEMPLOYEE = E.FLDREC_NUM
AND PPDx.FLDPHYSICAL = '110' AND
PPDx.FLDDATEDUE <= getdate()
LEFT OUTER JOIN REQEXAM PPDL
ON PPDL.FLDEMPLOYEE = E.FLDREC_NUM
AND PPDL.FLDPHYSICAL = '110'
LEFT OUTER JOIN REQEXAM TBSSx
ON TBSSx.FLDEMPLOYEE = E.FLDREC_NUM
AND TBSSx.FLDPHYSICAL = 'TBSS' AND
TBSSx.FLDDATEDUE <= getdate()
LEFT OUTER JOIN REQEXAM TBSSL
ON TBSSL.FLDEMPLOYEE = E.FLDREC_NUM
AND TBSSL.FLDPHYSICAL = 'TBSS'
LEFT OUTER JOIN REQEXAM CDUEx
ON CDUEx.FLDEMPLOYEE = E.FLDREC_NUM
AND CDUEx.FLDPHYSICAL = '109' AND
CDUEx.FLDDATEDUE <= getdate()
LEFT OUTER JOIN EMP S
ON S.FLDREC_NUM = E.FLDREC_NUM
WHERE E.FLDCOMP = #company
AND E.FLDSTATUS = 'A'
AND E.FLDSUPRNAME <> ' '
AND E.FLDID <> ' '
GROUP BY E.FLDSUPRNAME
ORDER BY E.FLDSUPRNAME
If I add ID,NAME and Dept on select and group by , SUM(1) will turn to 1 or 0, so I'm getting either 100% or 0% for all supervisors.
Any help on this is really appreciated.
thanks for your time.
USE an UNION, add blank columns to your first query and remove the order by:
SELECT (CASE WHEN ID IS NULL THEN Supervisor ELSE '' END) ,ID, name,dept,Percent_Flu_Compliant,Percent_TB_Compliant,Percent_Fit_Compliant FROM
(
SELECT E.FLDSUPRNAME AS Supervisor, NULL as ID, NULL as name, NULL as dept
(...)
GROUP BY hiddensupervisor, Supervisor, ID, name, dept
UNION ALL
SELECT E.FLDSUPRNAME Supervisor, E.id, E.name, E.dept, NULL as Percent_Flu_Compliant, NULL as Percent_TB_Compliant, NULL asPercent_Fit_Compliant
FROM Employee
) as q
ORDER BY supervisor, (CASE WHEN ID IS NULL THEN 1 ELSE 0 END),ID
we add the hidden supervisor column to be able to fit employees under their supervisor but leave that field blank there (we also could not add it and use case in the outer query, dunno which one would be faster). Apparently we have to try with case

Resources