I'm trying something in Access via SQL using a LEFT JOIN but it doesn't seem to be working. Access keeps generating the error "JOIN expression not supported.".
What I'm trying to accomplish is as follows. I have a table with job cards and another table with costs as below.
JOBCARDS
ID JOBNAME
1 Job one
2 Job two
3 Job three
COSTS
ID TYPE COST JOB
1 PART 15.01 1
2 LABOUR 20.00 1
3 LABOUR 40.00 2
4 PART 34.54 3
5 PART 84.67 3
I'm trying to formulate an SQL query that will give me the following result:
QUERY
ID JOBNAME PARTS LABOUR
1 Job one 15.01 20.00
2 Job two 0.00 40.00
3 Job three 119.21 0.00
What I came up with:
SELECT
CARDS.[ID] AS [ID],
CARDS.[JOBNAME] AS [JOBNAME],
SUM (COSTS1.[COST]) AS [PARTS],
SUM (COSTS2.[COST]) AS [LABOUR]
FROM
(([JOBCARDS] CARDS LEFT JOIN [COSTS] COSTS1 ON COSTS1.[JOB]=CARDS.[ID] AND COSTS1.[TYPE]='PART')
LEFT JOIN [COSTS] COSTS2 ON COSTS2.[JOB]=CARDS.[ID] AND COSTS2.[TYPE]='LABOUR')
GROUP BY
CARDS.[ID], CARDS.[JOBNAME];
Access seems to be having problems with the part "COSTS1.[TYPE]='PART'".
Is there any way I can accomplish what I'm trying to do without using a LEFT JOIN?
Or does anyone spot the error?
This SQL will give the result.
The 0 values will be Null, but you could use NZ to replace that with a 0.
SELECT JobCards.ID
,JobName
,SUM(C2.Cost) AS Parts
,SUM(C1.Cost) AS Labour
FROM (JobCards LEFT JOIN Costs C1 ON (JobCards.ID = C1.Job AND C1.Type = 'Labour'))
LEFT JOIN Costs C2 ON (JobCards.ID = C2.Job AND C2.Type = 'Part')
GROUP BY JobCards.ID
,JobName
Edit:
Re-reading your SQL - you just forgot to put the brackets after the ON statements in your Join:
(COSTS1.[JOB]=CARDS.[ID] AND COSTS1.[TYPE]='PART')
SELECT
CARDS.[ID] AS [ID],
CARDS.[JOBNAME] AS [JOBNAME],
SUM (COSTS1.[COST]) AS [PARTS],
SUM (COSTS2.[COST]) AS [LABOUR]
FROM
(([JOBCARDS] CARDS LEFT JOIN [COSTS] COSTS1 ON (COSTS1.[JOB]=CARDS.[ID] AND COSTS1.[TYPE]='PART'))
LEFT JOIN [COSTS] COSTS2 ON (COSTS2.[JOB]=CARDS.[ID] AND COSTS2.[TYPE]='LABOUR'))
GROUP BY
CARDS.[ID], CARDS.[JOBNAME];
Edit 2: There's no need to put brackets around everything, or alias the field names if they're the same as the source field, or use the table names in the SELECT & WHERE clauses unless the field name appears in more than one table.
Here is a correlated sub-query example:
SELECT JOBCARDS.ID,
JOBCARDS.JOBNAME,
(SELECT SUM([COST]) FROM COSTS WHERE COSTS.JOB = JOBCARDS.ID AND COSTS.TYPE = 'PART') AS PARTS,
(SELECT SUM([COST]) FROM COSTS WHERE COSTS.JOB = JOBCARDS.ID AND COSTS.TYPE = 'LABOUR') AS LABOUR
FROM JOBCARDS;
Related
I'm trying to combine 3 different tables into one single row in a query but having some problems. Currently I have four tables; PaintSched, Painted_Log, Paint_Defect, and Paint_Inspection.
PaintSched - Single entry, when scheduler just schedules some parts to be painted
LOT QTY
1 150
2 100
Painted_Log - The paint department then takes the lot and says how many they were able to paint
LOT(FK) QTYPainted
1 145
2 100
Paint_Defect - Master List of defects for paint inspection after parts have been painted. We hand inspect all of our parts that we paint for quality.
DID Defect
1 Scratch
2 Paint Run
Paint_Inspection - Everytime a defect is found the inspector hits a correlating button and the following gets logged. Lot is FK and DID stands for Defect ID from Paint_Defect. QTY is always 1
Lot(FK) DID(FK) QTY
1 1 1
1 1 1
1 2 1
1 1 1
2 2 1
1 2 1
2 1 1
What I'm trying to get is the following output:
Lot Sched Painted Scratch Paint Run
1 150 145 3 2
2 100 100 1 1
I've tried the following to no avail:
SELECT PaintSched.Scheduled, PaintSched.Lot, PaintSched.qty, PaintSched.Is_Painted, Painted_Log.falloff
FROM PaintSched
INNER JOIN Painted_Log ON PaintSched.Lot = Painted_Log.lot
INNER JOIN MPA_Desc ON MPA_Desc.MPAID = PaintSched.MPAID
inner JOIN (
SELECT lot, sum(Paint_Inspection.qty) as seds
FROM Paint_Inspection
WHERE Paint_Inspection.Status = '1'
) AS seeds ON PaintSched.Lot = Paint_Inspection.Lot
SELECT
PS.Lot,
PS.Qty Sched,
Painted,
Scratch,
PaintRun
FROM PaintSched PS
LEFT JOIN (SELECT
Lot,
SUM(QTYPainted) Painted
FROM Painted_Log GROUP BY Lot) PL
ON PS.Lot = PL.Lot
LEFT JOIN (SELECT
Lot,
SUM(CASE WHEN DID = 1 THEN 1 ELSE 0 END) Scratch,
SUM(CASE WHEN DID = 2 THEN 1 ELSE 0 END) PaintRun
FROM Paint_Inspection GROUP BY Lot) PI
ON PS.Lot = PI.Lot
Try that in SQL Fiddle
The code above uses conditional sum to roll up the defect count by type before joining that to the lot id. If you have more than 2 statuses, you will need to update the above code accordingly.
Two things:
You should have a group by in the subquery
When you alias the subquery, you don't join it properly
See the edits to your query below:
SELECT
PaintSched.Scheduled,
PaintSched.Lot,
PaintSched.qty,
PaintSched.Is_Painted,
Painted_Log.falloff
FROM PaintSched
INNER JOIN Painted_Log ON PaintSched.Lot = Painted_Log.lot
INNER JOIN MPA_Desc ON MPA_Desc.MPAID = PaintSched.MPAID
INNER JOIN (
SELECT lot, sum(Paint_Inspection.qty) as seds
FROM Paint_Inspection
WHERE Paint_Inspection.Status = '1'
GROUP BY Paint_Inspection.lot -- Missing GROUP BY
) AS seeds
ON PaintSched.Lot = seeds.Lot
I work for a distribution centre in the uk and i've recently started using sql queries to access data directly from the db.
I've been tasked with writing a query that gives the total number of locations we have in each aisle (from table locn_hdr) and total number of locations emtpy in each of those aisles. I'vr managed to get all the info i need but by using twp seperate queries. I'm struggling to combine them into the below headers
Aisle - count of locations - count of empty locations
The two queries i have are below
Count of locations
select AISLE, COUNT(AISLE)
from LOCN_HDR LH
where LH.LOCN_CLASS = 'A'
and BAY >= '0030'
AND BAY <= '0230'
AND PICK_DETRM_ZONE LIKE 'HG%'
AND LH.AISLE <= 'QA'
group by aisle
Order by aisle;
Count of empties
SELECT aisle, COUNT(dsp_locn)
FROM locn_hdr lh
WHERE lh.locn_class = 'A'
AND bay >= '0030'
AND bay <= '0230'
AND pick_detrm_zone LIKE 'HG%'
AND lh.aisle <= 'QA'
AND NOT EXISTS
(SELECT 1
FROM wm_inventory wi
WHERE wi.location_id = lh.locn_id
AND wi.on_hand_qty > '0')
GROUP BY aisle
ORDER BY aisle;
Ideally indont just want the answer with the sql re written. I want to understand how i can do something similar myself in the future.
Thanks in advance guys! Sorry if I havent given enough info, go easy on me i'm new!
edit
Hi, thanks for the help first of all! It is appreciated. However, it isn't working as i need it. the column count(lh.aisle) is counting the number of empty locations rather than the total number of locations in the aisle. I had to change the sql slightly because i was getting error messages so i temporarily used
SELECT lh.AISLE, COUNT(lh.AISLE), COUNT(wi.location_id) -- count(lh.aisle) gives me the total empty locatins. Count(wi.location_id) gives me nothing...
FROM LOCN_HDR lh
LEFT OUTER JOIN wm_inventory wi ON wi.location_id = lh.locn_id AND wi.on_hand_qty > '0'
WHERE lh.LOCN_CLASS = 'A'
AND lh.BAY BETWEEN '0030' AND '0230'
AND lh.PICK_DETRM_ZONE LIKE 'HG%'
AND lh.AISLE <= 'QA'
AND wi.location_id IS NULL -- where there is no matching record for lh.locn_id with a quantity > 0
GROUP BY lh.AISLE
ORDER BY lh.AISLE;
This has given me a count of the empty locations which is fantastic. But I don't have a count of the total number of locations (empty or not).
Any more ideas would be appreciated!
SELECT lh.AISLE, COUNT(lh.AISLE), COUNT(wi.dsp_locn)
FROM LOCN_HDR lh
LEFT OUTER JOIN wm_inventory wi ON wi.location_id = lh.locn_id AND wi.on_hand_qty > '0'
WHERE lh.LOCN_CLASS = 'A'
AND lh.BAY BETWEEN '0030' AND '0230'
AND lh.PICK_DETRM_ZONE LIKE 'HG%'
AND lh.AISLE <= 'QA'
AND wi.ID IS NULL -- where there is no matching record for lh.locn_id with a quantity > 0
GROUP BY lh.AISLE
ORDER BY lh.AISLE;
Something similar to this should work, although I can't really test it without data. Your two queries are basically the same, with the notable exception of AND NOT EXISTS (... FROM wm_inventory ...).
Basically, you can LEFT OUTER JOIN this table on location_id and on_hand_qty. LEFT OUTER JOIN will return null where there is no match (instead of excluding them).
This means that if you have a record in LOCN_HDR with locn_id = 1, and you also have a record in wm_inventory with location_id = 1 but a quantity of 2, you will receive a NULL for this record.
Combined with the WHERE wi.ID IS NULL (change to suit the column on the wi table), this replaces the NOT EXISTS clause in the second query.
You may run into an issue with selecting COUNT(wi.dsp_locn) due to the GROUP BY, but you should be able to add GROUP BY lh.AISLE, wi.dsp_locn - this will combine all entries that have both the same lh.AISLE AND wi.dsp_locn.
If you need any additional explanation, please let me know - I'd be happy to give it a shot.
Table 1
jh."job-hdr"
job-date job-disp job-dept job-route job-id job-no
01/04/2013 6467 abc 123 22 81088
01/04/2013 6468 abc 987 36 82568
Table 2
rh."rec-charge"
charge-type rec-id base-sales-value
XYZ 22 700
Table 3
rc."rec-cost"
charge-type rec-id base-cost-value
XYZ 22 300
I need to be able to get the profit from this jobid of
700 - 300 = 400
This is where I have gotten up to
SELECT jh."job-date", jh."job-disp", jh."job-dept", jh."job-route", rc."charge-type",rh."charge-type",
SUM(rc."base-cost-value") as COSTS,
SUM(rh."base-sales-value") as SALES,
SUM(rh."base-sales-value") - SUM(rc."base-cost-value") as PROFIT
FROM MSN.PUB."rec-chg" rh, PUB."job-hdr" jh, pub."rec-cost" rc
WHERE jh."job-date" between '2013-04-01' and '2013-04-30'
and jh."job-id" = rc."rec-id"
and rc."rec-id" = rh."rec-id"
and jh."grp-id" = '0'
and jh."job-status"<>'D'
and jh."job-no" = '81088'
and rc."charge-type" = rh."charge-type"
Group by jh."job-date", jh."job-disp", jh."job-dept", jh."job-route",rc."charge- type",rh."charge-type"
This is not giving me great results at all and I know I am way off. I just need to be put in the right direction.
Update profit to:
SUM(rh."base-sales-value" - rc."base-cost-value") as PROFIT
And update your group by to:
group by jh."job-id", rc."rec-id", rh."rec-id"
This should give your the desired result (hopefully). Sorry didnt not have time to test it myself. The main focus is on group by, which should be applied on a field that would return multiple results for other fields you want to run the sum on.
Your question appears is a little ambiguous, as to whether you want the results by job or by charge type. In either case, you need to aggregate the results before doing the join. The following query does this at the job level:
SELECT jh."job-date", jh."job-disp", jh."job-dept", jh."job-route",
COSTS, SALES, SALES - COSTS as PROFIT
FROM PUB."job-hdr" jh left outer join
(select rh."rec-id", SUM(rh."base-sales-value") as SALES
from MSN.PUB."rec-chg" rh
group by rh."rec-id"
) rh
on jh."job-id" = rh."rec-id" left outer join
(select rc."rec-id", SUM(rc."base-cost-value") as COSTS
from pub."rec-cost" rc
group by rc."rec-id"
) rc
on jh."job-id" = rc."rec-id"
WHERE jh."grp-id" = '0' and
jh."job-status" <> 'D' and
jh."job-no" = '81088';
Notice that I replaced your implicit join syntax with explicit join syntax. The explicit version is much better, so you should learn to use it.
scenario : I have Three Tables(Prisoners,AddPaymentTransaction,WithdrawPaymentTransation)
Date in Tables : i have 1 row of prisoner with PrisonerID=5 and two rows in both other table,
i have wrote query to return there data if any prisoner have add some payment in there account or with draw any payment from there payment on same day or on different dates etc.
here is my query :
select at.PrisonerID ,at.Amount as AAmount,at.Date as ADate,wt.Amount as WAmount,wt.Date as WDate
from Prisoners p, AddPaymentTransaction at,WithdrawPaymentTransation wt
where p.PrisonerID=at.PrisonerID and p.PrisonerID=wt.PrisonerID and at.PrisonerID=wt.PrisonerID and at.PrisonerID=5
but it gives me 4 rows, 9 rows when i have 3 rows of data in each Table etc.
i want rows of data with out duplicate. any suggestions or help will be highly appreciated.
It looks like at.PrisonerID = wt.PrisonerID in your query might be what is causing all of the duplicates. I am guessing AddPaymentTransaction and WithdrawPaymentTransation should not be linked together. So, how about the following:
SELECT at.PrisonerID, at.Amount as AAmount, at.Date as ADate,
wt.Amount as WAmount, wt.Date as WDate
FROM Prisoners p
INNER JOIN AddPaymentTransaction at p.PrisonerID = at.PrisonerID
INNER JOIN WithdrawPaymentTransation wt ON p.PrisonerID = wt.PrisonerID
WHERE at.PrisonerID = 5
but this probably isn't going to give you exactly what you are looking for either. So maybe something like the following:
SELECT * FROM
(
SELECT p.PrisonerID, 'AddPayment' AS Type,
apt.Amount as TransAmount, apt.Date AS TransDate
FROM Prisoners p
INNER JOIN AddPaymentTransaction apt ON p.PrisonerID = apt.PrisonerID
WHERE apt.PrisonerID = 5
UNION
SELECT p.PrisonerID, 'WithdrawPayment' AS Type,
wt.Amount as TransAmount, wt.Date as TransDate
FROM Prisoners p
INNER JOIN WithdrawPaymentTransation wt ON p.PrisonerID = wt.PrisonerID
WHERE wt.PrisonerID = 5
) AS mq
ORDER BY mq.TransDate DESC
I have a stored procedure which takes 1 parameter, an ID number (systudentid).
The procedure returns 3 rows: a student’s academic counselor (AC), financial counselor (FC), and admissions counselor (EC) along with relevant contact information; 3 different people.
Certain students have ACs and FCs who are the same person, but the query will still return 3 rows.
AdvisorType|AdvisorLastName|AdvisorFirstName|(other data)|systaffID
AC DOE JOHN ..... 12345
AC DOE JOHN ..... 12345
EC SMITH JANE ..... 45678
Where in my code can I plug in the logic (and how, I'm a newbie with sql) so that when the systudentid passed to the procedure identifies a student having the same person for both AC and FC, it will display the results this way.
The advisor type is changed to "SSA" and only one of the records for the double-duty counselor is returned.
AdvisorType|AdvisorLastName|AdvisorFirstName|(other data)|SystaffID
SSA DOE JOHN ...... 12345
EC SMITH JANE ...... 45678
Here is my select statement:
SELECT
SyStaffGroup.Descrip AS AdvisorType
,SyStaff.LastName AS AdvisorLastName
,SyStaff.FirstName AS AdvisorFirstName
,SyStaff.Phone AS AdvisorPhone
,SyStaff.Ext AS AdvisorExtention
,SyStaff.eMail AS AdvisorEMail
,SyStaff.SyStaffID AS SyStaffID
FROM SyStaff (NOLOCK)
JOIN SyAdvisorByEnroll (NOLOCK)
ON SyAdvisorByEnroll.SyStaffID = SyStaff.SyStaffID
JOIN SyStaffGroup (NOLOCK)
ON SyStaffGroup.SyStaffGroupID = SyAdvisorByEnroll.SyStaffGroupID
JOIN AdEnroll (NOLOCK)
ON AdEnroll.AdEnrollID = SyAdvisorByEnroll.AdEnrollID
JOIN SyStudent (NOLOCK)
ON AdEnroll.SyStudentID = SyStudent.SyStudentId
WHERE
SyStaff.Active = 1
--AND
--syadvisorbyenroll.adenrollid = (
--SELECT adenrollid from dbo.fn_student_enrollment_activeenrollmentlist (#systudentid)
--)
AND adEnroll.adEnrollID IN (
SELECT adEnrollID FROM dbo.fn_Student_Enrollment_ActiveEnrollmentList(#SyStudentID)
)
AND SyAdvisorByEnroll.AdvisorModule IN ('AD','FA')
AND SyStaffGroup.Descrip IN ('AC - Academic Counselor', 'FC - Finance Counselors', 'EC - Adm. Counselor With Reg')
UNION
SELECT DISTINCT
'Admissions Counselor' AS AdvisorType
,SyStaff.LastName AS AdvisorLastName
,SyStaff.FirstName AS AdvisorFirstName
,SyStaff.Phone AS AdvisorPhone
,SyStaff.Ext AS AdvisorExtention
,SyStaff.eMail AS AdvisorEMail
,SyStaff.SyStaffID AS SyStaffID
FROM systudent
INNER JOIN AmRep ON SyStudent.AMREpID = AmREp.AMREpid
INNER JOIN SyStaff ON SyStaff.SyStaffID = AmRep.AmRepID
WHERE Systudent.SYStudentid = #systudentid
Any hints or suggested methods that I can either try or Google (I've tried searching but results are a lot more useful if I knew what to look for) would be greatly appreciated.
You can add a nested subquery to indicate which students have the same advisor filling multiple positions, and adjust the type selection accordingly. Here are the changed portions of your above query:
SELECT
CASE WHEN (mutiples.SyStaffID IS NOT NULL) THEN 'SSA'
ELSE SyStaffGroup.Descrip END AS AdvisorType
-- other columns omitted
FROM SyStaff (NOLOCK)
JOIN SyAdvisorByEnroll (NOLOCK)
ON SyAdvisorByEnroll.SyStaffID = SyStaff.SyStaffID
LEFT JOIN (
SELECT SyStaffID,AdEnrollID
FROM SyAdvisorByEnroll
GROUP BY SyStaffID,AdEnrollID
HAVING COUNT(DISTINCT SyStaffGroupID) > 1
) multiples
ON multiples.SyStaffID = SyAdvisorByEnroll.SyStaffID
AND multiples.AdEnrollID = SyAdvisorByEnroll.AdEnrollID
-- rest of query omitted
This might have a mistake or two, since you didn't include your table schema. The nested subquery, "multiples", contains all advisor / enrollee pairs where the advisor is in multiple groups. You left join against this and adjust the final type selection to "SSA" if there's a matching entry in the nested subquery.
An important note: as written, this will include two SSA rows for an eligible advisor / enrollee pair. However, the final results will not, because you are using a UNION in this query, which filters out duplicates, even if they're only present in one half of the union. If you change this to UNION ALL or eliminate the UNION entirely, you will need to add DISTINCT to the top of the query, like so:
SELECT DISTINCT CASE WHEN (mutiples.SyStaffID IS NOT NULL) ...