Pivot Query - Missing records - sql-server

I have a pivot query which works well until now, but there has been a requirement where I need to specify a condition in the unpivot query which would omit the rows and column values which are not matching with the condition and displays me null. However, I need to show those value as a part of final results.
I have tried to do union to include the missing values, but won't get the desired output. I am pasting my pivot query below along with the results which are displayed and which needs to be displayed as a result. Please help.
CURRENT QUERY
SELECT
OrderID, AccessName, Address1, Postcode
, Gen_Instr_1 AS "General Instructions for Install"
,Supplier_Name_1 AS "Supplier Name"
,Install_Job_Name_1 AS "Install Jobs"
,Install_Job_Status_1 AS "Install Job Status"
,Install_Job_Name_2 AS "EPR Jobs"
,Install_Job_Status_2 AS "EPR Job Status"
FROM
(
SELECT
OrderID, AccessName, Address1, Postcode
, col+'_'+CAST(rn AS VARCHAR(10)) col,
val
FROM
(
SELECT o.OrderID,
CAST(js.JobStatusID AS VARCHAR(50)) JobStatusId
, CAST(p.Name AS VARCHAR(50)) Install_Job_Name
, o.AccessName, o.Address1, o.Postcode
, CAST(oj.GeneralInstructions AS VARCHAR(50)) Gen_Instr
, CAST(s.CompanyName AS VARCHAR(50)) Supplier_Name
, oj.SupplierID
, CAST(js.Name AS VARCHAR(50)) Install_Job_Status
, ROW_NUMBER() OVER(PARTITION BY o.OrderID ORDER BY o.OrderID) rn
FROM
NEPCCO.Orders o
INNER JOIN NEPCCO.Clients c ON o.ClientID = c.ClientID
INNER JOIN NEPCCO.OrderJobs oj ON o.OrderID = oj.OrderID
INNER JOIN NEPCCO.Suppliers s ON oj.SupplierID = s.SupplierID
INNER JOIN NEPCCO.Products p ON oj.ProductID = p.ProductID
INNER JOIN NEPCCO.OrderStatus os ON o.OrderStatusID = os.OrderStatusID
INNER JOIN NEPCCO.JobStatus js ON oj.JobStatusID = js.JobStatusID
WHERE
o.OrderID IN (6981,6860,6982,6983) AND
(p.ProductID IN (35,36,37,38,38,40,41,42,43) OR p.ProductID IN (33,34))
AND s.CompanyName = 'Northern Gas Heating Ltd'
) d
UNPIVOT
(
val
FOR col IN (JobStatusId, Gen_Instr, Supplier_Name,Install_Job_Name, Install_Job_Status)
) un
) s
PIVOT
(
MAX(val)
FOR col IN (JobStatusID_1, Gen_Instr_1, Supplier_Name_1, Install_Job_Name_1, Install_Job_Status_1,
JobStatusID_2, Gen_Instr_2,
Install_Job_Name_2, Install_Job_Status_2
)
) piv
CURRENT RESULTS - SEE THE NULL VALUES IN LAST TWO COLUMNS
OrderID AccessName Address1 Postcode SupplierName Install Jobs Install Job Status EPR Jobs EPR Job Status
6981 Mrs Cespedes 73 Mill Lane WV11 1DQ Northern Gas Heating Ltd GC1 - 28 Complete NULL NULL
6983 Ms A Mirza 122 Pendleford Avenue WV6 9EN Northern Gas Heating Ltd GC1 - 28 Complete NULL NULL
Now, if I runn the inner unpivot query as below, I get following records/rows
Inner unpivot query
SELECT o.OrderID,
CAST(js.JobStatusID AS VARCHAR(50)) JobStatusId
, CAST(p.Name AS VARCHAR(50)) Install_Job_Name
, o.AccessName, o.Address1, o.Postcode
, CAST(oj.GeneralInstructions AS VARCHAR(50)) Gen_Instr
, CAST(s.CompanyName AS VARCHAR(50)) Supplier_Name
, oj.SupplierID
, CAST(js.Name AS VARCHAR(50)) Install_Job_Status
, ROW_NUMBER() OVER(PARTITION BY o.OrderID ORDER BY o.OrderID) rn1
FROM
NEPCCO.Orders o
INNER JOIN NEPCCO.Clients c ON o.ClientID = c.ClientID
INNER JOIN NEPCCO.OrderJobs oj ON o.OrderID = oj.OrderID
INNER JOIN NEPCCO.Suppliers s ON oj.SupplierID = s.SupplierID
INNER JOIN NEPCCO.Products p ON oj.ProductID = p.ProductID
INNER JOIN NEPCCO.OrderStatus os ON o.OrderStatusID = os.OrderStatusID
INNER JOIN NEPCCO.JobStatus js ON oj.JobStatusID = js.JobStatusID
WHERE
o.OrderID IN (6981,6860,6982,6983) AND
(p.ProductID IN (35,36,37,38,38,40,41,42,43) OR p.ProductID IN (33,34))
that produces following results
OrderID AccessName Address1 Postcode SupplierName Install Jobs Install Job Status EPR Jobs EPR Job Status
6860 6 AW EPR 01625555555 1 Gorsey Road SK9 5DU OGP 14 Cancelled 1
6981 4 AW EPR Mrs Cespedes 73 Mill Lane WV11 1DQ Ian Barnhurst 1 Complete 1
6981 4 GC1 - 28 Mrs Cespedes 73 Mill Lane WV11 1DQ Northern Gas Heating Ltd 403 Complete 2
6982 4 AW EPR Installer Mr N Singh 115 Oxbarn Avenue WV3 7HQ Northern Gas 414 Complete 1
6983 4 AW EPR Installer Ms A Mirza 122 Pendleford Avenue WV6 9EN Northern Gas 414 Complete 1
6983 4 GC1 - 28 Ms A Mirza 122 Pendleford Avenue WV6 9EN Northern Gas Heating Ltd 403 Complete 2
Problem
Now, if you see carefully the above result set, which has the order id's 6860, 6982, which is not included as a part of above result because it hasn't got the supplier name as Northern Gas Heating Ltd, moreover, the results which are displayed on first query, omits the values from order id's 6981, 6983, also, because they have different suppliers.
Also, if you notice, with the records being displayed in first query, the values with row number 2 are not included.
I tried my best but failed. #bluefeet, your expertise highly required over here. Any clarifications please ask.

Related

SQL Server return distinct rows?

I'm running this SQL statement:
SELECT
s.indx, S.custid, S.date, S.qty, S.item, S.price, S.extprice,
S.salestax, S.linetotal, S.salenbr, C.company, P.MOP
FROM
sales S
JOIN
cust C ON S.custid = C.custid
JOIN
pmts P ON S.salenbr = p.salenbr
WHERE
(s.salenbr = 16749)
It's returning this result set:
indx custid date qty item price extprice salestax linetotal salenbr company MOP
170835 695 2021-09-27 10:00:44.000 1.00 1X4X12 7.85 7.85 0.75 8.60 16749 COUNTER SALE CS
170835 695 2021-09-27 10:00:44.000 1.00 1X4X12 7.85 7.85 0.75 8.60 16749 COUNTER SALE CC
170836 695 2021-09-27 10:00:44.000 1.00 1X6X12 11.62 11.62 1.10 12.72 16749 COUNTER SALE CS
170836 695 2021-09-27 10:00:44.000 1.00 1X6X12 11.62 11.62 1.10 12.72 16749 COUNTER SALE CC
I want to just pull the rows where the method of payment "MOP" is different. I'm using the data to run a report and need it just with distinct or unique MOP's.
Thank You
You could use ROW_NUMBER here an arbitrarily take the "first" record from each MOP group, according to some order:
WITH cte AS (
SELECT s.indx, S.custid, S.date, S.qty, S.item, S.price, S.extprice,
S.salestax, S.linetotal, S.salenbr, C.company, P.MOP,
ROW_NUMBER() OVER (PARTITION BY P.MOP ORDER BY S.date) rn
FROM sales S
INNER JOIN cust C ON S.custid = C.custid
INNER JOIN pmts P ON S.salenbr = P.salenbr
WHERE S.salenbr = 16749
)
SELECT indx, custid, date, qty, item, price, exitprice,
salestax, linetotal, salenbr, company, MOP
FROM cte
WHERE rn = 1;
So, what you want to do will probably work better using a Common Table Expression or CTE. Something like this:
WITH CTE_Sales AS
(
SELECT
s.indx, S.custid, S.date, S.qty, S.item, S.price, S.extprice,
S.salestax, S.linetotal, S.salenbr, C.company, P.MOP,
COUNT(1) AS salesCount
FROM
sales S
JOIN
cust C ON S.custid = C.custid
JOIN
pmts P ON S.salenbr = p.salenbr
GROUP BY
s.indx, S.custid, S.date, S.qty, S.item, S.price, S.extprice,
S.salestax, S.linetotal, S.salenbr, C.company, P.MOP
)
SELECT
indx, custid, date, qty, item, price, extprice,
salestax, linetotal, salenbr, company
FROM
CTE_Sales
GROUP BY
indx, custid, date, qty, item, price, extprice,
salestax, linetotal, salenbr, company
HAVING
salesCount > 1
What this does is that the CTE contains all your data, which makes it easier to not deal with joins every time. You've also done a group by so you know how many records you have for the same sale.
Then, when you pull the data, you're grouping the records without the MOP. Since the first record is grouped with MOP and the second is grouped without, you know that the MOPs are different.
Me thinks I need to go back and do some redesigning in my code and data tables SMor you are correct about the details vs. the transactions. Live and learn :) Thanks to you all for taking the time to respond. I work solo so It's always great to hear other comments and ideas. Thanks!

SQL NESTED JOIN ISSUES

I'm having a heck of a time getting my query to work properly. I have 3 tables (ORDERS, ORDERSITEMS, ORDERPAYMENTS) that I'm trying to build a report for monthly sales taxes due which will look like this:
MONTH YEAR TOTAL RECEIPTS EXEMPT RECEIPTS NON-EXEMPT RECEIPTS SALES TAX
1 2020 $5,000 $4,500 $500 $31.25
TOTAL RECEIPTS: To get this number you have to add together all of the C.OrderPayments_Amount for the given time frame, in this case MONTH(C.OrderPayments_Date) = 1 AND YEAR(C.OrderPayments_Date) = 2020
EXEMPT RECEIPTS: You have to determine if an item is taxable (eg. digital files are not sales taxable, physical prints are). To get this you have determine if the item is taxable by checking the B.OrdersItems_ItemChargeSalesTax. If this field is 0 it does not get charged sales tax and if it is 1 then it does. You then have to filter to only get ORDERSITEMS for the Jan 2020 time frame using by grouping by the C.OrderPayments_Date column that have the B.OrdersItems_ItemChargeSalesTax = 0 and finally add the B.OrdersItems_Total together.
NON-EXEMPT RECEIPTS: To get this number you do the same exact thing for EXEMPT RECEIPTS above except you look for B.OrdersItems_ItemChargeSalesTax = 1 and add the B.OrdersItems_Total together.
SALES TAX: To get this number you use the same date filter as before MONTH(C.OrderPayments_Date) = 1 AND YEAR(C.OrderPayments_Date) = 2020 and then add the A.Order_SalesTax column together.
The first query I have listed is working fine to bring me the total taxes paid and the total income for the month (right now I have hard coded the WHERE statement but that is going to be applied via filters on my list page). What I
need to get from the ORDERSITEMS table is a field called ORDERSITEMS_ItemTotal and sum that field so it is a single line entry on the query. I have seen another person do a nested join. Any suggestions would be greatly appreciated.
**ORDERS TABLE "A"**
Order_ID,
Order_SalesTax,
stateTaxAbbreviation
**ORDERSITEMS TABLE "B"**
Order_FK,
OrdersItems_ItemChargeSalesTax,
OrdersItems_Total
NOTE: In the ORDERSITEMS table a single Order_FK may appear several times as there can be many items on an order
**ORDERPAYMENTS TABLE "C"**
Order_FK,
OrderPayments_PaymentDate,
OrderPayments_Amount
NOTE: In the ORDERPAYMENTS table a single Order_FK may appear several times as there can be multiple payments on an order
While writing this out it seems to be an easy task but when I attempt to put it all together the numbers are wrong because it is adding entries multiple times because there are multiple items on an order and thus it is adding the total payment every time.
Here is the code that I've been tinkering with and I would really appreciate any guidance. Thank you in advance and hopefully I've explained my situation clearly enough.
Select
a.stateTaxAbbreviation AS StateAbbr,
MONTH(c.OrderPayments_Date) AS PaymentMonth,
YEAR(c.OrderPayments_Date) AS PaymentYear,
SUM(c.OrderPayments_Amount) AS TotalPayments,
SUM(a.Order_SalesTax) AS sales_tax
FROM dbo.ORDERS a
INNER JOIN ORDERPAYMENTS as c ON c.Order_FK = a.Order_ID
LEFT OUTER JOIN ORDERITEMS b on b.Order_FK = a.Order_ID
WHERE a.stateTaxAbbreviation = 'MA' AND Month(b.OrderPayments_Date) = 1 AND YEAR(b.OrderPayments_Date) = 2020
GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)
You should probably write 2 queries, one where you join the ORDERPAYMENTS table, and another where you join the ORDERITEMS table. Then you can combine them with UNION ALL.
Something like this:
SELECT StateAbbr,PaymentMonth,PaymentYear,SUM(TotalPayments),SUM(sales_tax),SUM(OrdersItems_Total)
FROM (
Select
a.stateTaxAbbreviation AS StateAbbr,
MONTH(c.OrderPayments_Date) AS PaymentMonth,
YEAR(c.OrderPayments_Date) AS PaymentYear,
SUM(c.OrderPayments_Amount) AS TotalPayments,
SUM(a.Order_SalesTax) AS sales_tax,
0 as OrdersItems_Total
FROM dbo.ORDERS a
INNER JOIN ORDERPAYMENTS as c ON c.Order_FK = a.Order_ID
WHERE a.stateTaxAbbreviation = 'MA' AND Month(c.OrderPayments_Date) = 1 AND YEAR(c.OrderPayments_Date) = 2020
GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)
UNION ALL
Select
a.stateTaxAbbreviation AS StateAbbr,
MONTH(c.OrderPayments_Date) AS PaymentMonth,
YEAR(c.OrderPayments_Date) AS PaymentYear,
0 AS TotalPayments,
0 AS sales_tax,
SUM(B.OrdersItems_Total) as OrdersItems_Total
FROM dbo.ORDERS a
INNER JOIN ORDERITEMS b on b.Order_FK = a.Order_ID
WHERE a.stateTaxAbbreviation = 'MA' AND Month(b.OrderPayments_Date) = 1 AND YEAR(b.OrderPayments_Date) = 2020
GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)
)t
GROUP BY StateAbbr,PaymentMonth,PaymentYear
Thanks to Wouter for pointing me in the right direction. After looking at his suggestion I went back and evaluated what I needed and I create the solution that worked that was based on his idea. Thanks for your patience Wouter, your insight helped a lot!
Select StateAbbr, OrderYear, OrderMonth, SUM(TotalSales) As TotalSales, SUM(TotalSales)-SUM(TaxableRevenue) As ExemptRevenue, SUM(TaxableRevenue) As TaxableRevenue, SUM(SalesTax) As SalesTax
FROM (
Select
/*Get Total Sales and Total Sales Tax Collected*/
a.stateTaxAbbreviation AS StateAbbr,
MONTH(a.Order_Date) As OrderMonth,
YEAR(a.Order_Date) As OrderYear,
SUM((a.Order_TotalBaseSale + a.Order_Shipping) - (((a.Order_PercentDiscount*a.Order_TotalBaseSale)/100) + a.Order_DollarDiscount)) As TotalSales,
SUM(0) As ExemptRevenue,
Sum(0) As TaxableRevenue,
SUM(a.Order_SalesTax) AS SalesTax
FROM dbo.ORDERS a
WHERE a.Order_Status != 'Cancelled'
Group By a.stateTaxAbbreviation, MONTH(a.Order_Date), YEAR(a.Order_Date)
UNION ALL
Select
/*GET EXEMPT ORDERS*/
a.stateTaxAbbreviation AS StateAbbr,
MONTH(a.Order_Date) As OrderMonth,
YEAR(a.Order_Date) As OrderYear,
Sum(0) As TotalSales,
Sum(OrdersItems_ItemTotal) AS ExemptRevenue,
Sum(0) AS TaxableRevenue,
Sum(0) As SalesTax
FROM ORDERSITEMS b
LEFT JOIN ORDERS a ON Order_ID = b.Order_FK
WHERE b.OrdersItems_ItemChargeSalesTax = 0 and a.Order_Status != 'Cancelled'
Group By a.stateTaxAbbreviation, MONTH(a.Order_Date), YEAR(a.Order_Date)
UNION ALL
Select
/*GET NON-EXEMPT ORDERS*/
a.stateTaxAbbreviation AS StateAbbr,
MONTH(a.Order_Date) As OrderMonth,
YEAR(a.Order_Date) As OrderYear,
SUM(0) As TotalSales,
SUM(0) AS ExemptRevenue,
Sum(OrdersItems_ItemTotal) AS TaxableRevenue,
Sum(0) As SalesTax
FROM ORDERSITEMS b
LEFT JOIN ORDERS a ON Order_ID = b.Order_FK
WHERE b.OrdersItems_ItemChargeSalesTax <> 0 and a.Order_Status != 'Cancelled'
Group By a.stateTaxAbbreviation, MONTH(a.Order_Date), YEAR(a.Order_Date)
)t
GROUP BY StateAbbr, OrderMonth, OrderYear
ORDER BY StateAbbr ASC, OrderYear DESC, OrderMonth ASC

How to get top 1 record of each group based on where clause using group by column in SQL Server

I want the top 1 record of each group, group column is imei. If user has multiple devices, it should show the latest record of all devices.
SQL
SELECT TOP 1
p.imei, DEVICEID, timestatmp, ph, do, temp
FROM
dbo.pond AS p
INNER JOIN
customerdevices AS cd ON p.imei = cd.imei
INNER JOIN
users AS u ON cd.CustomerId = u.CustomerId
WHERE
u.username = 'bob'
ORDER BY
timestatmp DESC
Sample data
imei DEVICEID timestatmp ph do temp
-----------------------------------------------------------------------
869668021752476 1027 2020-03-16 04:33:00.617 7.86 5.04 22.52
869668021752476 1027 2020-03-16 04:03:00.957 7.88 4.99 22.59
869668021732924 1025 2020-03-16 03:57:01.130 7.39 5.40 21.85
Expected output:
imei DEVICEID timestatmp ph do temp
-----------------------------------------------------------------------
869668021752476 1027 2020-03-16 04:33:00.617 7.86 5.04 22.52
869668021732924 1025 2020-03-16 03:57:01.130 7.39 5.40 21.85
You may use TOP 1 WITH TIES in conjunction with ROW_NUMBER, to stick with your current approach:
SELECT TOP 1 WITH TIES p.imei, DEVICEID, timestatmp, ph, do, temp
FROM dbo.pond AS p
INNER JOIN customerdevices AS cd
ON p.imei = cd.imei
INNER JOIN users AS u
ON cd.CustomerId = u.CustomerId
WHERE u.username = 'bob'
ORDER BY
ROW_NUMBER() OVER (PARTITION BY p.imei, DEVICEID ORDER BY timestatmp DESC);
This trick works because all records retained would have a row number of value of 1, which would only occur for the latest record, for each imei and DEVICEID group.
you can use ROW_NUMBER() function
SELECT
imei,
DEVICEID,
timestatmp,
ph,
do,
temp FROM
(
SELECT
p.imei,
DEVICEID,
timestatmp,
ph,
do,
temp,
RN=ROW_NUMBER() OVER( PARTITION BY p.imei ORDER BY timestatmp DESC)
FROM dbo.pond as p
inner JOIN customerdevices as cd ON p.imei = cd.imei inner Join users
as u on cd.CustomerId = u.CustomerId where u.username='bob' )
T
Where T.RN=1 order by timestatmp desc

How to select distinct from union result with condition

I want to select distinct vendor with chase if there are two vendor with status register and not register then the choosen one is vendor with status register but if only one vendor then just select it,
I'm using sql server 2017
SELECT
pv.vendor_id,pv.vendor_name,'Not Registered' as registration_status
FROM
proposal_vendor as pv
UNION
SELECT bv.vendor_id,bv.vendor_name,bv.registration_status
FROM
bidding_vendor as bv
WHERE
bv.bidding_header_id = 97
48 vendor a Register
48 vendor a Not Registered
4110 vendor b Register
4110 vendor b Not Registered
4197 vendor c Not Registered
what i'm expected is
48 vendor a Register
4110 vendor b Register
4197 vendor c Not Registered
You can get your expected output using row number and case statement. If you have two registered then you can use rank, else you can use row number if you want just one row per vendor id.
select vendor_id, vendor_name, registration_status from (
SELECT bv.vendor_id,bv.vendor_name,bv.registration_status, row_number() over (partition by bv.vendor_id order by case when registration_status = 'Register' then 1 else 2) rownum
FROM
bidding_vendor as bv) t
where t.rownum = 1
SELECT pv.vendor_id,
pv.vendor_name,
'Not Registered' as registration_status
FROM proposal_vendor as pv
WHERE NOT EXISTS(SELECT 1
FROM bidding_vendor bv
WHERE bv.vendor_id = pv.vendor_id
AND bv.bidding_header_id = 97)
UNION ALL
SELECT bv.vendor_id,
bv.vendor_name,
bv.registration_status
FROM bidding_vendor as bv
WHERE bv.bidding_header_id = 97
There are multiple possibilities here.
You can make your main query a derived table source for your results query
SELECT pv.vendor_id,
pv.vendor_name, MAX(registration_status) as registration_status
FROM (
SELECT
pv.vendor_id,pv.vendor_name,'Not Registered' as registration_status
FROM
proposal_vendor as pv
UNION
SELECT bv.vendor_id,bv.vendor_name,bv.registration_status
FROM
bidding_vendor as bv
WHERE
bv.bidding_header_id = 97
) src
You can use Outer Join logic
SELECT pv.vendor_id,
pv.vendor_name,
CASE WHEN bv.vendor_id is null
THEN 'Not '
END + 'Registered' as registration_status
FROM proposal_vendor as pv
FULL OUTER JOIN bidding_vendor as bv
ON pv.vendor_id = bv.vendor_id
WHERE pv.vendor_id = 97
OR bv.vendor_id = 97
Or you can choose another from perhaps a half dozen different techniques.

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