SQL Join and Where Issue - sql

So im having the following issue, when i run the following query
SELECT ClientSubId,ClientType,ClientStatus,AddressLine1,AddressLine2,
CityName,PostalCode,StateProvinceCode,
ClientFirstName,ClientLastName, BillManagerName
FROM CLIENT
JOIN
CLIENTADDRESS
ON CLIENT.ClientIdent = CLIENTADDRESS.ReferenceIdent
JOIN
CLIENTINDIVIDUAL
ON CLIENT.ClientIdent = CLIENTINDIVIDUAL.ClientIdent
JOIN
CLIENTPRACTICE
ON CLIENT.ClientIdent = CLIENTPRACTICE.ClientIdent
Im getting back all results that match all fields, witch is correct, However when i apply the where clause at the end
WHERE
CLIENT.ClientIdSubId = '48079'
I get back no results. Im confused as to why i dont get back any results when i apply the Where clause, but without it i get all the results and that ID number is apart of those results.
Results without the WHERE
Results With the Where

Your query is pretty simple. I can only see two possible issues:
There's no CLIENT with ClienIdSubId that is equal to '48079'.
There is a CLIENT with that criteria, but there's no matching row in CLIENTADDRESS, in CLIENTINDIVIDUAL, or CLIENTPRACTICE. Make sure there are matching rows on each table since you are using INNER JOINS.

Sorry to all i had the right query ClientIdSubId was suppose to be ClientSubId. Instead of ClientIdSubId.

Related

Query with Totals Query results as criteria returns the expected number of results squared

Background
I am building an Access 2010 database that has a table [ControllerAdjustments] that keeps track of all adjustments made to controllers with an [AdjustmentID] autonumber field, a [ControllerID] field, an [AdjustmentDate] field, [Setpoint] field, and a [Power] field. The [Power] field represents the power level when the adjustment was made. Ultimately I need two queries to return two sets of results, one query should return the current status of all controllers (basically the most recent adjustment made on each controller) and the other should return the most recent adjustment made on each controller where power level is 100%. I plan to use each of these queries to feed a report. Note: field names changed slightly for convenience when typing, full names given in the code blocks...
Method
I focused on the Current Query first, and figured I would just copy it and make necessary changes to create a 100% Query. I started with a totals query on the [ControllerAdjustments] table, that had [ControllerID] as a Group By field and [AdjustmentDate] as a field that returned the Max value. This query returns exactly the number of records I expected, and after reviewing the sample bogus data I put in the table to check it, it seems to return exactly the records I need. I then created a Select Query that returned all the fields I want in my Current Report, namely the [ControllerAdjustments] table and the related records in upstream related tables. I then set the criteria for the [ControllerID] field in my Select Query to equal [Total_CurrentContAdjs]![ControllerID] and the [AdjustmentDate] in the Select Query to [Total_CurrentContAdjs]![MaxOfAdjustmentDate]. Running this query returns exactly what I want. The SQL for this query is below:
SELECT List_Units.UnitID, List_EDTanks.TankNameShort, List_Controllers.ControllerType, ControllerAdjustments.AdjustmentDate, ControllerAdjustments.ControllerSetpoint, ControllerAdjustments.RxPower
FROM Total_ContAdjsCurrent, ((List_Units INNER JOIN List_EDTanks ON List_Units.UnitID = List_EDTanks.UnitID) INNER JOIN List_Controllers ON List_EDTanks.EDTankID = List_Controllers.EDTankID) INNER JOIN ControllerAdjustments ON List_Controllers.ControllerID = ControllerAdjustments.ControllerID
WHERE (((ControllerAdjustments.AdjustmentDate)=[Total_ContAdjsCurrent]![MaxOfAdjustmentDate]) AND ((ControllerAdjustments.ControllerID)=[Total_ContAdjsCurrent]![ControllerID]))
ORDER BY List_Units.Unit, List_EDTanks.TankSortOrder, List_Controllers.ControllerType DESC;
I then copied the Totals query and added a column for Power, selected Where, unchecked show, and put in 100 for criteria. This works as expected. I then copied my select query, and changed the criteria fields to direct to my new 100% Totals query. This is where my problems begin.
Problem
The second 100% Query does not seem to like the criteria, as it initially throws out the familiar parameter window. This is the SQL Statement for the second query, virtually the same except for referring to the 100% Totals query:
SELECT List_Units.UnitID, List_EDTanks.TankNameShort, List_Controllers.ControllerType, ControllerAdjustments.AdjustmentDate, ControllerAdjustments.ControllerSetpoint, ControllerAdjustments.RxPower
FROM Total_ContAdjsCurrent, Total_ContAdjsStdyState, ((List_Units INNER JOIN List_EDTanks ON List_Units.UnitID = List_EDTanks.UnitID) INNER JOIN List_Controllers ON List_EDTanks.EDTankID = List_Controllers.EDTankID) INNER JOIN ControllerAdjustments ON List_Controllers.ControllerID = ControllerAdjustments.ControllerID
WHERE (((ControllerAdjustments.AdjustmentDate)=[Total_ContAdjsStdyState]![MaxOfAdjustmentDate]) AND ((ControllerAdjustments.ControllerID)=[Total_ContAdjsStdyState]![ControllerID]))
ORDER BY List_Units.Unit, List_EDTanks.TankSortOrder, List_Controllers.ControllerType DESC;
Initially, Access did not add my Totals query into the show table box in design view, because its results were not directly used in the Select Query. So, I added the Totals query to the top, and that allowed my query to run without asking for parameters, but now it returns the number of results I was expecting squared. Basically if I am expecting 3 records: 1, 2, and 3, it is giving me: 1, 1, 1, 2, 2, 2, 3, 3, and 3. For the life of me I cannot figure out why it is doing this, especially because the exact same setup for my Current Query returns exactly what is expected... I thought maybe the where clause in my totals query had something to do with it, so I created a Select Query for the [ControllerAdjustments] table that returned all records with 100 for power. I then used this query for my totals query instead of the totals query itself, but this did not do anything different. I am at a loss, and not sure what else I can do to get the results I want. Any suggestions welcome, thank you!
I solved this by simply starting over from scratch and rebuilding my 100% query. Reviewing the SQL statements, they look identical, however for some reason my query now returns the right number of records. I have no idea why this worked, and am still curious what went wrong in the first place if anyone with time available cares to dig into it, but the original problem statement has been corrected--even if I have no idea how I did it haha...

Rails 5 equivalent for this complex SQL query?

I have a query working the way I want, by executing SQL directly, but am curious (just for my own learning purposes) if this same thing could be done in an ActiveRecord statement?
The part I'm struggling with the most is the COALESCE part of this query, which just makes sure that any NULL values from the LEFT JOIN are counted as zeros instead, to keep the summation in order.
Any ideas? I'm using Postgres.
SELECT Inventories.id, Inventories.name, Inventories.unit_of_measure,
COALESCE(Sum(Stocks.count),0) as totalcount
FROM Inventories
LEFT JOIN Stocks
ON Inventories.id = Stocks.inventory_id
WHERE Inventories.property = 'material' AND Inventories.organization_id = #{current_organization.id}
GROUP BY Inventories.id, Stocks.inventory_id
ORDER BY totalcount ASC
LIMIT(5)")
This is the closest I've gotten for an AR equivalent. When I try to add a sum or something like it, that's when it errors out.
#lowmaterials = current_organization.inventories.materials.left_joins(:stocks).group(:id, :inventory_id).order(count: :asc).limit(5)
You can use ActiveRecord::QueryMethods#select:
your_relation.select("column1, column2, COALESCE(1,2) AS column3").left_joins...

MS Access Update SQL Query Extremely Slow and Multiplying the Amount of Records Updated

I am stumped on how to make this query run more efficiently/correctly. Here is the query first and then I can describe the tables that are involved:
UPDATE agg_pivot_test AS p
LEFT JOIN jd_cleaning AS c
ON c.Formerly = IIF(c.Formerly LIKE '*or*', '*' & p.LyFinalCode & '*', CStr(p.LyFinalCode))
SET p.CyFinalCode = c.FinalCode
WHERE p.CyFinalCode IS NULL AND c.Formerly IS NOT NULL;
agg_pivot_test has 200 rows of data and only 99 fit the criteria of WHERE p.CyFinalCode IS NULL. The JOIN needs some explaining. It is an IIF because some genius decided to link last year's data to this year's data using Formerly. It is a string because sometimes multiple items have been consolidated down to one so they use "or" (e.g., 632 or 631 or 630). So if I want to match this year's data I have to use Formerly to match last year's LyFinalCode. So this year the code might be 629, but I have to use the Formerly to map the items that were 632, 631, or 630 to the new code. Make sense? That is why the ON has an IIF. Also, Formerly is a string and LyFinalCode is an integer... fun.
Anyway, when you run the query it says it is updating 1807 records when again, there are only 200 records and only 99 that fit the criteria.
Any suggestions about what this is happening or how to fix it?
An interesting problem. I don't think I've ever come across something quite like this before.
I'm guessing what's happening is that rows where CyFinalCode is null, are being matched multiple times by the join statement, and thus the join expression is calculating a cartesian product of row-matches, and this is the basis of the rows updated message. It seems odd, as I would have expected access to complain about multiple row matches, when row matches should only be 1:1 in an update statement.
I would suggest rewriting the query (with this join) as a select statement, and seeing what the query gives you in the way of output; Something like:
SELECT p.*, c.*
FROM agg_pivot_test p LEFT JOIN jd_cleaning c
ON c.Formerly = IIF(c.Formerly LIKE '*or*', '*' & p.LyFinalCode & '*', CStr(p.LyFinalCode))
WHERE p.CyFinalCode IS NULL AND c.Formerly IS NOT NULL
I'm also inclined to suggest changing "... & p.LyFinalCode & ..." to "... & CStr(p.LyFinalCode) & ..." - though I can't really see why it should make a difference.
The only other thing I can think to suggest is change the join a bit: (this isnt guaranteed to be better necessarily - though it might be)
UPDATE agg_pivot_test AS p LEFT JOIN jd_cleaning AS c
ON (c.Formerly = CStr(p.LyFinalCode) OR InStr(c.Formerly, CStr(p.LyFinalCode)) > 0)
(Given the syntax of your statement, I assume this sql is running within access via ODBC; in which case this should be fine. If I'm wrong the sql is running server side, you'll need to change InStr to SubString.)

Repeated results from an access query

I am new to Access and acually to db's ,
I'm trying to perform a db for recording the results of a really huge survey. So far everything is ok but now that i am designing the Queries I am getting repeated results and I don't know why.
My SQL Statement is:
SELECT T_VALORACIO.IdValoracio, T_ENQUESTA.Treballador,
T_VALORACIO.IdValPreu
FROM (T_ALSECA INNER JOIN T_VALORACIO ON T_ALSECA.idTipus =
T_VALORACIO.idTipus) INNER JOIN T_ENQUESTA ON T_ALSECA.IdAlseca =
T_ENQUESTA.idAlSeca
WHERE (((T_ENQUESTA.Treballador)=True) AND ((T_VALORACIO.IdValPreu)=4));
I would expect getting the results that fit both cases, but the results that fit just the first case are also shown.
Thanks in advance !
Try using instead:
SELECT DISTINCT
This removes duplicate rows.

Microsoft Access Query - Can't select records when adding a date to query

I am trying to compare two tables in MS Access 2010, and select records from one table (tmp_import_table) which don't exist in the second table (referrals). This works fine with the following query:
SELECT tmp_import_table.F2, tmp_import_table.F12, tmp_import_table.F13, tmp_import_table.RefDate
FROM tmp_import_table LEFT JOIN referrals ON tmp_import_table.[F2] = referrals.[ext_referral_no]
WHERE (((referrals.ext_referral_no) Is Null));
and results in the following dataset:
However, I now need to add a second criteria to the WHERE clause in the query, and select only records which occur after a certain date, which is stored in referrals.referral_date (date/time field) I have written the following query:
SELECT tmp_import_table.F2, tmp_import_table.F12, tmp_import_table.F13, tmp_import_table.RefDate
FROM tmp_import_table LEFT JOIN referrals ON tmp_import_table.[F2] = referrals.[ext_referral_no]
WHERE (((referrals.ext_referral_no) Is Null) AND ((referrals.referral_date)>#9/10/2014#));
But the query always ends with an empty dataset! I've tried all sorts of permutations of it, but always end up with the same empty result! In addition I've tried swearing, banging my head against the wall, and alcohol, but none of these seem to have worked either...
Can anybody spot an obvious problem with my query?
Thanks for looking!
Seb
You are doing left join and selecting tmp_import_table.RefDate in the first query. But filtering by referrals.referral_date in the second one which may be/are NULLs. Change to:
....AND ((tmp_import_table.referral_date)>#9/10/2014#));