SQL Access Sentence - sql

I been trying to use this sentences that i made in SQL Server Management Studio, on access with no luck, after hours googling, i think they use different languages, can someone help me turn these in Access language?
select c.id_client 'Client ID',
c.client_name 'First Name'
c.client_lname 'Last Name'
from client c join bills b
on c.id_client = b.id_client join bill_detail d
on d.bill_num=b.bill_num
where month (b.date)=3
and year(b.date)= year(getdate())
group by c.id_client, c.client_name,c.client_lname
having d.price > (select avg(prirce) from bill_detail)
select s.id_seller 'Seller ID',
s.seller_name 'First Name',
s.seller_lname 'Last Name',
avg(quantity*d.price),
from sellers s join bills b
on v.id_seller=b.id_seller join bill_detail d
on b.bill_num = d.bill_num
group by s.id_seller, s.seller_name, s.seller_lname
having avg (quantity*d.price) < (select avg(quantity*d.price) from
bill_detail)
select date 'Date',
sum(quantity) 'Tickets Sold',
sum(quantity*d.price) 'Total Amount Sold',
avg(quantity*d.price) 'Average Amount Sold',
from bills b join bill_detail d
on b.bill_num = d.bill_num
group by date
Sry, they were in spanish, hence the awfull english. And thanks in advance.

Useful references:
Converting Access Queries to SQL Server
T-SQL Equivalents for Microsoft Access VBA Functions
I think these will work.. (it's been a while)
SELECT
client.id_client [client id]
, client.client_name [first name]
, client.client_lname [last name]
FROM (client
JOIN bills ON client.id_client = bills.id_client)
JOIN bill_detail ON bill_detail.bill_num = bills.bill_num
WHERE MONTH(bills.date) = 3
AND YEAR(bills.date) = YEAR(DATE())
GROUP BY
client.id_client
, client.client_name
, client.client_lname
HAVING d.price > (
SELECT
AVG(prirce)
FROM bill_detail
)
;
For some reason Access likes parentheses in the from clause. No idea why. There should be MONTH() & YEAR() . Don't recall if Access like table aliases, so I removed them and don't use single quotes for column labels (don't do this is SQL Server either).
SELECT
sellers.id_seller [seller id]
, sellers.seller_name [first name]
, sellers.seller_lname [last name]
, AVG(quantity * bill_detail.price)
FROM (sellers
JOIN bills ON v.id_seller = bills.id_seller)
JOIN bill_detail ON bills.bill_num = bill_detail.bill_num
GROUP BY
sellers.id_seller
, sellers.seller_name
, sellers.seller_lname
HAVING AVG(quantity * bill_detail.price) < (
SELECT
AVG(quantity * bill_detail.price)
FROM bill_detail
)
;
Aside from table & column aliases changes these 2 should be ok.
SELECT
datex [date]
, SUM(quantity) [tickets sold]
, SUM(quantity * bill_detail.price) [total amount sold]
, AVG(quantity * bill_detail.price) [average amount sold]
FROM (bills
JOIN bill_detail ON bills.bill_num = bill_detail.bill_num)
GROUP BY
datex
;

having d.price > (select avg(prirce) from bill_detail)
I think you should change it to avg(price) instead of avg(prirce).
(Must be spelling mistake only)

Related

Return a Calculated Field from a Cross-Join Query

I am using sp_addlinkedsrvlogin to execute a cross-join query on two different SQL Servers (our payroll server and our production server). The first query returns how many hours each employee logged on the time clock (payroll server). The second query returns how many hours that same employee was logged into work orders.
I would like to create a calculated column called Employee_Utilization that divides WO_Hours by Payroll_Hours. Any tips on how to do this in this Cross Join query would be great.
EXEC sp_addlinkedsrvlogin 'PAYROLLSERVER', 'false', NULL, '**', '**********'
SELECT * FROM
(
SELECT
C.EMPLOYEE AS [Employee ID]
,E.FIRSTNAME
,E.LASTNAME
,C.[PEREND]
,C.[CATEGORY]
,C.[AUDTORG]
,C.[EARDEDTYPE]
,C.[EARDEDDATE]
,SUM(DISTINCT C.[HOURS]) AS [Payroll_Hours]
FROM [PAYROLLSERVER].[SagePayroll].[dbo].[UPCHKD] C JOIN [PAYROLLSERVER01].[SagePayroll_SUD].[dbo].[UPHHAU] E ON C.EMPLOYEE = E.EMPLOYEE
WHERE C.CATEGORY = '2' AND C.PEREND = '20221210'
GROUP BY
C.EMPLOYEE
,E.FIRSTNAME
,E.LASTNAME
,C.[PEREND]
,C.[CATEGORY]
,C.[AUDTORG]
,C.[EARDEDTYPE]
,C.[EARDEDDATE]
) A
CROSS JOIN
(
SELECT [Employee ID],SUM([Labor Run Hours]) AS [WO_Hours]
FROM [********].[*********].[dbo].[WorkOrders_Labor]
WHERE [Date Worked] > '11/26/22' AND [Date Worked] < '12/11/22'
GROUP BY [Employee ID]
) B
WHERE A.[Employee ID] = B.[Employee ID]
``

Calculated overpay amount base on date condition -SQL Server

I have a code in SQL to retrieve member who has pay date after termination date, and now I also need to calculate the total amount paid after the termination date. How can I achieve that?
There are 2 table, member table:
The final out come I want is:
Currently I am able to retrieve other columns but the Sum(Rcvd Amount)
Select Member_ID
, Term_DT
, RCVD.MAX_RCVD_DT
From Membership a
Left Join
(
Select Member_ID
, MAX(RCVD_DT) as MAX_RCVD_DT
from received
group by Member_ID
)
AS RCVD on RCVD.Member_ID = a.Member_ID
WHERE RCVD.MAX_RCVD_DT >= Term_DT
I think this is just a join -- with an inequality condition -- and aggregation:
select m.memberid, sum(r.rcvd_amount)
from membership m join
received r
on m.memberid = r.memberid and
r.recvd_date > m.term_date
group by m.memberid;
You should use below query:
select m.memberid, max(m.Term_DT) Term_DT, MAX(r.RCVD_DT) as MAX_RCVD_DT, sum(r.rcvd_amount)
from membership m join
received r
on m.memberid = r.memberid and
r.recvd_date > m.term_date
group by m.memberid;
Something like this
select m.Member_ID [Member ID], m.Term_DT [Term Date],
sum(r.RCVD_AMOUNT) [Rcvd Amount], max(r.RCVD_DT) [Latest Rcvd Date]
from membership m
join received r on m.Member_ID = r.Member_ID
and r.RCVD_DT >= m.Term_DT
group by m.Member_ID, m.Term_DT;

Pivoting to append the last 6 payments for 24 loans

I am building a query in Microsoft sql server where I want to find the active loans as well as some information on them. I have built out a common table expression that gives me the correct population. Now I need to get the last 6 payments starting from today. I have a another common table expression that gives all the payments and the payment data received but I am not sure how to pivot and append the last 6 payments such that I have something like this:
This is what the query and output looks like for the common table expression where I can get c1,...,c6.
SELECT Account,Total,CONVERT(datetime,DateRec) [Date Received]
FROM mars.dbo.vw_PaymentHistory PH
WHERE PH.SourceTyp not like '%fundin%' and PH.SourceTyp not like '%draw%'
which gives this (but much more):
Here is the whole query I am working from:
Declare #monthEnding date = '3/31/2020',
#monthStart date = '3/1/2020';
WITH Active_Loans as (
SELECT
la.Account,
la.LoanStatus,
la.PrinBal,
isnull(b.Amount, 0) [DUPB],
la.PrinBal + isnull(b.Amount, 0) [TotalUPB],
l.NoteOwner,
pt.[Partition],
l.paidoffdate,
la.[First Name],
la.[Last Name],
la.PmtPI,
la.PmtImpound,
la.NextDueDate,
la.MaturityDate,
la.NoteOwner as [Note Owner]
FROM MARS_DW..vw_vw_Loans_ArchiveEOM la
LEFT JOIN MARS_DW..vw_DUPBByLoan b on b.Account = la.Account
AND b.ArchiveDate = la.ArchiveDate
LEFT JOIN MARS..vw_Loans l on l.Account = la.Account
LEFT JOIN Portfolio_Analytics..partition_table pt on pt.Noteowner = l.NoteOwner
WHERE la.MonthEnding = #monthEnding
AND la.isActive = 1
AND la.PaidOffDate is null
AND la.LoanStatus NOT LIKE 'BK Payment Plan'
AND la.LoanStatus NOT LIKE 'Prelim'
AND la.LoanStatus NOT like 'trailing claims'
AND la.Account NOT IN (
SELECT account
FROM MARS..vw_Loans
WHERE servicexferdate <=
DATEADD(dd, - 1, DATEADD(mm, DATEDIFF(mm, 0, #monthStart) + 1, 0))
AND PaidOffDate BETWEEN #monthStart AND DATEADD(dd, - 1, DATEADD(mm, DATEDIFF(mm, 0, #monthStart) + 1, 0))
)
UNION
(
SELECT l.account
,la.LoanStatus
,la.PrinBal
,isnull(b.Amount, 0) [DUPB]
,la.PrinBal + isnull(b.Amount, 0) [TotalUPB]
,l.NoteOwner
,pt.[Partition]
,l.PaidOffDate
,la.[First Name]
,la.[Last Name]
,la.PmtPI
,la.PmtImpound
,la.NextDueDate
,la.MaturityDate
,la.NoteOwner as [Note Owner]
FROM MARS..vw_Loans l
LEFT JOIN MARS_DW..vw_vw_Loans_ArchiveEOM la on la.Account = l.Account
LEFT JOIN MARS_DW..vw_DUPBByLoan b on b.Account = la.Account
LEFT JOIN Portfolio_Analytics..partition_table pt on pt.Noteowner = l.NoteOwner
AND b.ArchiveDate = la.ArchiveDate
WHERE l.servicexferdate < #monthEnding
AND l.PaidOffDate > #monthEnding
AND la.MonthEnding = #monthEnding
AND la.LoanStatus NOT like 'trailing claims'
AND la.LoanStatus NOT like 'Inactive - REO/FC'
AND pt.[Partition] IS NOT NULL
)
)
,
payments as
(
SELECT Account,Total,CONVERT(datetime,DateRec) [Date Received]
FROM mars.dbo.vw_PaymentHistory PH
WHERE PH.SourceTyp not like '%fundin%' and PH.SourceTyp not like '%draw%'
)
SELECT
rptpop.Account
, rptpop.[First Name]
, rptpop.[Last Name]
, '$' + CONVERT (VARCHAR (12), rptpop.PmtPI+rptpop.PmtImpound, 1) as PITI
,'$' + CONVERT (VARCHAR (12), rptpop.TotalUPB, 1) as [Total UPB]
, CONVERT(VARCHAR(10),rptpop.NextDueDate,101) as [Next Due Date]
, CONVERT(VARCHAR(10),rptpop.MaturityDate,101) as [Maturity Date]
, rptpop.[Note Owner]
FROM Active_Loans as rptpop
LEFT JOIN payments as pmt on pmt.Account = rptpop.Account
WHERE
rptpop.Partition = 'GAEA'
AND rptpop.LoanStatus = 'Current'
AND rptpop.[Last Name] NOT LIKE '%CRE%'
AND pmt.[Date Received] BETWEEN #monthStart AND #monthEnding
EDIT:
Based on the answer below I was able to do this:
payments as
(
SELECT ROW_NUMBER() OVER(Partition By Account ORDER BY CONVERT(datetime,DateRec) DESC) AS [RowNumber], Total, Account
FROM mars.dbo.vw_PaymentHistory
)
,
get_payment1 as
(
SELECT * FROM payments
where RowNumber = 1
)
Which gives me numbers but what I do not understand is whether 1.) This is indeed correct and 2.) Assuming it is correct how do is it getting the most recent date? Perhaps its the order by clause?
I see a couple of way to solve the problem. I can share the approach using pseudo code.
Create Payments CTE , something like SELECT ROW_NUMBER() OVER(Partition By Account ORDER BY ReceivedDate DESC) . Then create 6 CTE's that use the above CTE with Row_Number 1 thru 6. Then simply use those using Left Join in your query, joining on Account#. This will add c1-c6 columns.
A second approach can be to use the same Payments CTE but instead of multiple CTEs, find a way to use UNPIVOT unpivot (Amount for Rows in (1,2,3,4,5,6) ) u;

Comma-separated List of Results

I have a fairly basic query that essentially returns a SUM total for invoice line net, for each customer, where there was a certain discount given.
As part of this, I want to return the invoice numbers that each discount applied to, as a comma separated list.
This is essential as it's being fed into another piece of software that only accepts the data in this format.
I could format in Excel as this is where the data will end up, however I'd rather do it in the query directly.
I'm getting my head muddled trying to use the FOR XML PATH function to do this.
Below is the current query, which returns one row per Discount Group, Customer, Discount % given with the sum totals
Field for invoice number is invoice_header.ih_number
SELECT variant_discount_group.vdg_node_path AS 'Discount Group' ,
customer_detail.cd_statement_name AS 'Customer Name' ,
invoice_line_item.ili_discount_percent AS 'Discount' ,
SUM(( CASE WHEN invoice_header.ih_credit = 1 THEN -1
ELSE 1
END ) * invoice_line_item.ili_qty) AS 'Qty' ,
SUM(( CASE WHEN invoice_header.ih_credit = 1 THEN -1
ELSE 1
END ) * invoice_line_item.ili_net) AS 'Total Net'
FROM invoice_header
JOIN invoice_line_item ON invoice_line_item.ili_ih_id = invoice_header.ih_id
JOIN variant_detail ON variant_detail.vad_id = invoice_line_item.ili_vad_id
JOIN variant_setting ON variant_setting.vas_vad_id = variant_detail.vad_id
JOIN customer_detail ON customer_detail.cd_id = invoice_header.ih_cd_id
LEFT JOIN variant_discount_group ON variant_discount_group.vdg_id = variant_setting.vas_vdg_id
WHERE invoice_header.ih_datetime BETWEEN #DateFrom
AND #DateTo
AND ISNULL(variant_discount_group.vdg_node_path, '') LIKE #VDGroup
+ '%'
AND invoice_line_item.ili_discount_percent BETWEEN #DiscFrom
AND #DiscTo
GROUP BY variant_discount_group.vdg_node_path ,
customer_detail.cd_statement_name ,
invoice_line_item.ili_discount_percent
ORDER BY variant_discount_group.vdg_node_path ,
customer_detail.cd_statement_name ,
invoice_line_item.ili_discount_percent
try this
WITH cte
AS ( SELECT variant_discount_group.vdg_node_path AS [Discount Group] ,
customer_detail.cd_statement_name AS [Customer Name] ,
invoice_line_item.ili_discount_percent AS [Discount] ,
( CASE WHEN invoice_header.ih_credit = 1 THEN -1
ELSE 1
END ) * invoice_line_item.ili_qty AS [Qty] ,
( CASE WHEN invoice_header.ih_credit = 1 THEN -1
ELSE 1
END ) * invoice_line_item.ili_net AS [Total Net] ,
invoice_header.ih_number AS [invoice]
FROM invoice_header
JOIN invoice_line_item ON invoice_line_item.ili_ih_id = invoice_header.ih_id
JOIN variant_detail ON variant_detail.vad_id = invoice_line_item.ili_vad_id
JOIN variant_setting ON variant_setting.vas_vad_id = variant_detail.vad_id
JOIN customer_detail ON customer_detail.cd_id = invoice_header.ih_cd_id
LEFT JOIN variant_discount_group ON variant_discount_group.vdg_id = variant_setting.vas_vdg_id
WHERE invoice_header.ih_datetime BETWEEN #DateFrom
AND #DateTo
AND ISNULL(variant_discount_group.vdg_node_path, '') LIKE #VDGroup
+ '%'
AND invoice_line_item.ili_discount_percent BETWEEN #DiscFrom
AND
#DiscTo
)
SELECT a.[Discount Group] ,
a.[Customer Name] ,
a.[Discount] ,
SUM(a.[Qty]) AS Qty ,
SUM(a.[Total Net]) AS [Total Net] ,
SUBSTRING(( SELECT ', ' + CONVERT(VARCHAR, b.[invoice])
FROM (SELECT DISTINCT
[invoice],
[Discount Group],
[Customer Name],
[Discount]
FROM cte) AS b
WHERE a.[Discount Group] = b.[Discount Group]
AND a.[Customer Name] = b.[Customer Name]
AND a.[Discount] = b.[Discount]
FOR
XML PATH('')
), 2, 1000) AS [List of invoices]
FROM cte AS a
GROUP BY a.[Discount Group] ,
a.[Customer Name] ,
a.[Discount]
ORDER BY a.[Discount Group] ,
a.[Customer Name] ,
a.[Discount]
I don't know about performance issues but you could create a function returning a VARCHAR. Call that function in your select statement and as parameter give your reference for your invoicenumbers.
in the Function you would have a cursor for all rows of Invoicenumbers and iterate over it and concatenate into the return value.
This is probably quick and dirty and ressource intensive.

Values Inexplicably multiplying by a power of 15 when performing a join?

So I started building a query that joins 5 separate tables together to get values to multiply and sum. However, I seem to be facing a rather odd issue. Whenever I attempt to join a certain table to my query, suddenly all of my values are multiplied by 15, the counts, the sums, etc. I'm trying to figure out what is causing all these extra runs. Any ideas?
Full Query
USE Facilities_Database
DECLARE #minimumDate DATE
DECLARE #maximumDate DATE
SET #minimumDate = '2014/12/11'
SET #maximumDate = '2014/12/15'
SELECT tab4.TypeName AS 'Labor Type'
,tab1.Building
,CAST(#minimumDate AS nvarchar(255)) + ' - ' + CAST(#maximumDate AS nvarchar(255)) AS 'Date Range'
,Count(tab1.CHSRNumber) AS 'Number of CHSRs'
,ISNULL(SUM(tab5.[Item Cost] * tab3.[Amount Used]),0) AS 'Total Material Cost'
,ISNULL(SUM(tab2.[Hour Worked] * tab2.[Hourly CHSR Labor Rate]),0) AS 'Total Labor Cost'
FROM [Facilities].[HardwareSupportRequest] tab1
JOIN Facilities.tblCHSRLaborPerCHSR tab2
ON tab1.CHSRNumber = tab2.[CHSR #]
JOIN Facilities.tblMaterialUsed tab3
ON tab1.CHSRNumber = tab3.[CHSR #]
JOIN Facilities.LaborTypes tab4
ON tab2.LaborTypeId = tab4.Id
JOIN Facilities.tblMaterial tab5
ON tab3.MaterialId = tab5.Id
WHERE tab1.ActualCompleteDate BETWEEN #minimumDate AND #maximumDate AND tab4.TypeName IS NOT NULL
GROUP BY tab4.TypeName,Building
ORDER BY Building,tab4.TypeName
Working Query:
USE Facilities_Database
SELECT tab1.Building
,COUNT(*) AS 'CHSR Count'
,SUM(tab2.[Hour Worked] * 40) AS 'Labor Cost'
FROM [Facilities].[HardwareSupportRequest] tab1
INNER JOIN Facilities.tblCHSRLaborPerCHSR tab2 ON
tab1.CHSRNumber = tab2.[CHSR #]
INNER JOIN Facilities.LaborTypes tab3 ON
tab2.LaborTypeId = tab3.Id
--INNER JOIN Facilities.tblMaterialUsed tab4 ON
--tab4.[CHSR #] = tab1.CHSRNumber
--INNER JOIN Facilities.tblMaterial tab5 ON
-- tab4.MaterialId = tab5.Id
WHERE ActualCompleteDate BETWEEN '2014/12/11' AND '2014/12/15'
GROUP BY tab1.Building,tab3.TypeName
The table that causes the problems is tblMaterialsUsed.
Thanks for any assistance.
You've got insufficient JOIN criteria resulting in one row joining to multiple rows.
If the following query results in two different numbers, then you know that JOIN is to blame:
SELECT COUNT(*),COUNT(DISTINCT [CHSR #])
FROM Facilities.tblMaterialUsed
You need to then determine how to exclude the extra records by adding to your JOIN criteria or perhaps aggregating in a subquery first.
Update:
To aggregate first you can use a cte or subquery to aggregate by CHSR # then join to that cte/subquery:
;WITH Materials AS (SELECT mat.[CHSR #]
,ISNULL(SUM(tab5.[Item Cost] * tab3.[Amount Used]),0) AS Total_Material_Cost
FROM Facilities.tblMaterialUsed tab3
JOIN Facilities.tblMaterial tab5
ON tab3.MaterialId = tab5.Id
GROUP BY mat.[CHSR #]
)
SELECT tab4.TypeName AS 'Labor Type'
,tab1.Building
,CAST(#minimumDate AS nvarchar(255)) + ' - ' + CAST(#maximumDate AS nvarchar(255)) AS 'Date Range'
,Count(tab1.CHSRNumber) AS 'Number of CHSRs'
,SUM(mat.Total_Material_Cost) AS 'Total Material Cost'
,ISNULL(SUM(tab2.[Hour Worked] * tab2.[Hourly CHSR Labor Rate]),0) AS 'Total Labor Cost'
FROM [Facilities].[HardwareSupportRequest] tab1
JOIN Facilities.tblCHSRLaborPerCHSR tab2
ON tab1.CHSRNumber = tab2.[CHSR #]
JOIN Facilities.LaborTypes tab4
ON tab2.LaborTypeId = tab4.Id
JOIN Materials mat
ON tab1.CHSRNumber = mat.[CHSR #]
WHERE tab1.ActualCompleteDate BETWEEN #minimumDate AND #maximumDate AND tab4.TypeName IS NOT NULL
GROUP BY tab4.TypeName,Building
ORDER BY Building,tab4.TypeName
If adding a JOIN multiplies the results of GROUP BY operations, then the JOIN is returning more than 1 row per JOIN criteria. Either narrow it down (maybe you are missing 1 or more JOIN fields?) or add more fields to the GROUP BY to change the granularity of what is being aggregated.
The issue is that you have a list of Materials User per each [CHSR #]. Those rows cause a "Cartesian Product" such that the other rows are duplicated per each row in tblMaterialUsed. Hence the Total Material Cost field was probably correct while the Number of CHSRs and Total Labor Cost were multiplied. Essentially, you need to group data at the same level of granularity, which means 1-to-1 across CHSRNumber / [CHSR #]
The following should solve this issue. If it doesn't, that would be due to more than 1 row per CHSRNumber / [CHSR #] in the main query (which is getting JOINed with the 1 row per CHSRNumber / [CHSR #] of the material CTE). In this case, you would apply the same theory to the main query by creating a second CTE for that aggregation and then just JOIN both of those results in the new main query. (and I have updated the query below to incorporate that change as it is doubtful that it wouldn't be needed)
;WITH material AS
(
SELECT mu.[CHSR #],
ISNULL(SUM(mtrl.[Item Cost] * mu.[Amount Used]),0) AS [MaterialCost]
FROM Facilities.tblMaterialUsed mu
INNER JOIN Facilities.tblMaterial mtrl
ON mu.MaterialId = mtrl.Id
GROUP BY mu.[CHSR #]
), labour AS
(
SELECT tab1.CHSRNumber,
tab4.TypeName,
tab1.Building,
ISNULL(SUM(tab2.[Hour Worked] * tab2.[Hourly CHSR Labor Rate]),0) AS [LaborCost]
FROM [Facilities].[HardwareSupportRequest] tab1
JOIN Facilities.tblCHSRLaborPerCHSR tab2
ON tab1.CHSRNumber = tab2.[CHSR #]
JOIN Facilities.LaborTypes tab4
ON tab2.LaborTypeId = tab4.Id
WHERE tab1.ActualCompleteDate BETWEEN #minimumDate AND #maximumDate
AND tab4.TypeName IS NOT NULL
GROUP BY tab1.CHSRNumber, tab4.TypeName, tab1.Building
)
SELECT labour.TypeName AS [Labor Type],
labour.Building,
CAST(#minimumDate AS NVARCHAR(255)) + ' - '
+ CAST(#maximumDate AS NVARCHAR(255)) AS [Date Range],
COUNT(labour.[CHSRNumber]) AS [Number of CHSRs],
SUM(material.[MaterialCost]) AS [Total Material Cost],
SUM(labour.[LaborCost]) AS [Total Labor Cost]
FROM labour
INNER JOIN material
ON labour.CHSRNumber = material.[CHSR #]
GROUP BY labour.TypeName, labour.Building
ORDER BY labour.Building, labour.TypeName;
If you want this in a View, instead use an Inline Table-Valued Functions by adding the following to the beginning:
CREATE FUNCTION GetCosts (#minimumDate DATE, #maximumDate DATE)
RETURNS TABLE
AS RETURN
And
remove the ; before the ;WITH
remove the ORDER BY
Also, it would be a huge benefit if you used acronyms for table aliases instead of tab1, tab2, etc as it would make the query much easier to read, especially given that the same table in both queries isn't even the same tab#.
It appears I can use subqueries to fix this issue
USE Facilities_Database
DECLARE #minimumDate DATE
DECLARE #maximumDate DATE
SET #minimumDate = '2012/12/11'
SET #maximumDate = '2014/12/15'
SELECT LaborTypes.TypeName AS 'Labor Type'
,CHSRs.Building
,CAST(#minimumDate AS nvarchar(255)) + ' - ' + CAST(#maximumDate AS nvarchar(255)) AS 'Date Range'
,Count(CHSRs.CHSRNumber) AS 'Number of CHSRs'
,ISNULL(SUM(matUsed.cost),0) AS 'Total Material Cost'
,ISNULL(SUM(Labor.[Hour Worked] * Labor.[Hourly CHSR Labor Rate]),0) AS 'Total Labor Cost'
FROM [Facilities].[HardwareSupportRequest] CHSRs
JOIN Facilities.tblCHSRLaborPerCHSR Labor
ON CHSRs.CHSRNumber = Labor.[CHSR #]
JOIN (SELECT ROUND(SUM(matU.[Amount Used] * mat.[Item Cost] * 1.05417 * 1.15),2) AS cost, [CHSR #]
FROM Facilities.tblMaterialUsed matU
JOIN Facilities.tblMaterial mat ON
matU.MaterialId = mat.Id
GROUP BY matU.[CHSR #]) matUsed ON
matUsed.[CHSR #] = CHSRs.CHSRNumber
--JOIN Facilities.tblMaterialUsed tab3
-- ON CHSRs.CHSRNumber = tab3.[CHSR #]
JOIN Facilities.LaborTypes LaborTypes
ON Labor.LaborTypeId = LaborTypes.Id
--JOIN Facilities.tblMaterial tab5
-- ON tab3.MaterialId = tab5.Id
WHERE CHSRs.ActualCompleteDate BETWEEN #minimumDate AND #maximumDate AND LaborTypes.TypeName IS NOT NULL
GROUP BY LaborTypes.TypeName,Building
ORDER BY Building,LaborTypes.TypeName