How to Select Sum and Multiple Columns - sql

Problem: I have a piece of code that joins two tables on whether the amounts for the respective references from both add to zero. The issue is that I don't know how to include more columns in the resulting query.
SELECT *
FROM (SELECT PayRef, SUM(MerchAmount) AS FAmount
FROM qryPaymentReferenceConversion
GROUP BY PayRef) AS qryPaymentReferenceConversion
INNER JOIN (SELECT Reference, SUM(TransAmount) AS BAmount
FROM tblBankStatementRegisterMaster GROUP BY Reference) AS tblBankStatementRegisterMaster
ON tblBankStatementRegisterMaster.Reference =qryPaymentReferenceConversion.PayRef
WHERE qryPaymentReferenceConversion.FAmount + tblBankStatementRegisterMaster.BAmount = 0;
In addition, when I try this alternative, I get a syntax error. Problem: Whenever I compile the code below, I receive a syntax error in the JOIN operation. Is this because I am selecting all fields rather than specifying the Reference field from the bank table? If so, how do I select all tables while maintaining the relationship?
SELECT tblBankStatementRegisterMaster.*, TransAmt
FROM tblBankStatementRegisterMaster AS BAmount
INNER JOIN (SELECT PayRef, Sum(MerchAmt) AS FAmount
FROM qryPaymentReferenceConversion GROUP BY PayRef)
ON tblBankStatementRegisterMaster.Reference = qryPaymentReferenceConversion.PayRef
WHERE qryPaymentReferenceConversion.FAmount + tblBankStatementRegisterMaster.BAmount = 0;

Related

Handling Duplicate Column Name Issue in MariaDB Count Query

I am getting an error on the query I'm running to get a count in MariaDB. This is the error:
Error Code: 1060. Duplicate column name 'id_number'
And this is my SQL code:
SELECT COUNT(*) as count FROM (
SELECT * FROM ((cr.customers
INNER JOIN (progress_notes_details
INNER JOIN progress_notes ON progress_notes_details.progress_note_id = progress_notes.id_number)
ON customers.id_number = progress_notes.c_id)
INNER JOIN open_balances ON progress_notes_details.id_number = open_balances.progress_notes_detail_id)
INNER JOIN
customer_payer_xref ON customers.id_number = customer_payer_xref.c_id
WHERE
(((progress_notes_details.qb_isbillable) IS NULL
OR (progress_notes_details.qb_isbillable) <> 1)
AND ((progress_notes_details.date_of_visit) BETWEEN coverage_start AND coverage_end)
AND ((progress_notes_details.dynamics_status) = 3)
AND ((customer_payer_xref.payer_id) = 23)
AND ((customer_payer_xref.primary_secondary_account_type) = 1))
) AS qdat
Can this be resolved via aliases? If so, it's unclear to me where to add them. In the main query? In the subquery?
Also, to clarify, I just inherited this code - and yes, it's bracket-happy.
Alias customers table as c and use it as c.id_number at one of the places it will remove that duplicate error as this is the only table you are using multiple times with idnumber hence duplicate
Remove the outer query:
SELECT COUNT(*)
FROM ((cr.customers . . .
Clearly, you have tables with the same column name. This causes a problem with SELECT *.
All the parentheses are probably not needed for the JOINs as well.

Selecting ambiguous column from subquery with postgres join inside

I have the following query:
select x.id0
from (
select *
from sessions
inner join clicked_products on sessions.id0 = clicked_products.session_id0
) x;
Since id0 is in both sessions and clicked_products, I get the expected error:
column reference "id0" is ambiguous
However, to fix this problem in the past I simply needed to specify a table. In this situation, I tried:
select sessions.id0
from (
select *
from sessions
inner join clicked_products on sessions.id0 = clicked_products.session_id0
) x;
However, this results in the following error:
missing FROM-clause entry for table "sessions"
How do I return just the id0 column from the above query?
Note: I realize I can trivially solve the problem by getting rid of the subquery all together:
select sessions.id0
from sessions
inner join clicked_products on sessions.id0 = clicked_products.session_id0;
However, I need to do further aggregations and so do need to keep the subquery syntax.
The only way you can do that is by using aliases for the columns returned from the subquery so that the names are no longer ambiguous.
Qualifying the column with the table name does not work, because sessions is not visible at that point (only x is).
True, this way you cannot use SELECT *, but you shouldn't do that anyway. For a reason why, your query is a wonderful example:
Imagine that you have a query like yours that works, and then somebody adds a new column with the same name as a column in the other table. Then your query suddenly and mysteriously breaks.
Avoid SELECT *. It is ok for ad-hoc queries, but not in code.
select x.id from
(select sessions.id0 as id, clicked_products.* from sessions
inner join
clicked_products on
sessions.id0 = clicked_products.session_id0 ) x;
However, you have to specify other columns from the table sessions since you cannot use SELECT *
I assume:
select x.id from (select sessions.id0 id
from sessions
inner join clicked_products
on sessions.id0 = clicked_products.session_id0 ) x;
should work.
Other option is to use Common Table Expression which are more readable and easier to test.
But still need alias or selecting unique column names.
In general selecting everything with * is not a good idea -- reading all columns is waste of IO.

SQL subquery multiple times error

I am making a subquery but I am getting a strange error
The column 'RealEstateID' was specified multiple times for 'NotSold'.
here is my code
SELECT *
FROM
(SELECT *
FROM RealEstatesInfo AS REI
LEFT JOIN Purchases AS P
ON P.RealEstateID=REI.RealEstateID
WHERE DateBought IS NULL) AS NotSold
INNER JOIN OwnerEstate AS OE
ON OE.RealEstateID=NotSold.RealEstateID
It's on SQL server by the way.
That's because there will be 2 realestiteids in your subquery. You need to change it to explicitly list the columns from both table and only include 1 realestateid. It doesn't matter which as you use it for your join.
If you're very Lazy you can select rei.* and only name the p cols apart from realestateid.
Btw select * is probably never a good idea in sub queries or derived tables or ctes.

Getting way more results than expected in SQL left join query

My code is such:
SELECT COUNT(*)
FROM earned_dollars a
LEFT JOIN product_reference b ON a.product_code = b.product_code
WHERE a.activity_year = '2015'
I'm trying to match two tables based on their product codes. I would expect the same number of results back from this as total records in table a (with a year of 2015). But for some reason I'm getting close to 3 million.
Table a has about 40,000,000 records and table b has 2000. When I run this statement without the join I get 2,500,000 results, so I would expect this even with the left join, but somehow I'm getting 300,000,000. Any ideas? I even refered to the diagram in this post.
it means either your left join is using only part of foreign key, which causes row multiplication, or there are simply duplicate rows in the joined table.
use COUNT(DISTINCT a.product_code)
What is the question are are trying to answer with the tsql?
instead of select count(*) try select a.product_code, b.product_code. That will show you which records match and which don't.
Should also add a where b.product_code is not null. That should exclude the records that don't match.
b is the parent table and a is the child table? try a right join instead.
Or use the table's unique identifier, i.e.
SELECT COUNT(a.earned_dollars_id)
Not sure what your datamodel looks like and how it is structured, but i'm guessing you only care about earned_dollars?
SELECT COUNT(*)
FROM earned_dollars a
WHERE a.activity_year = '2015'
and exists (select 1 from product_reference b ON a.product_code = b.product_code)

MS Access - SQL nested inner join

Just need to ask for your help, I have been having some problems with MS Access, I'm trying to create a nested INNER JOIN to perform a query. All of the fields that I need are showing up, however when I try to add a new entry it gives me an error
Can't Add Records Join key of table is not in record set.
Here's my code:
SELECT
Applicant_ID, Complete_Name, Date_of_Birth, Date_of_Application, Gender,
City_Address, Position_Applied, Civil_Status, Age, Educational_Attainment,
Table_JuniorRecruiter.Junior_Recruiter_ID, Junior_Recruiter_Name, Exam_Remarks,
Table_Exam.Exam_Number
FROM
(Table_Applicant
INNER JOIN
Table_Exam ON Table_Applicant.Exam_Number = Table_Exam.Exam_Number)
INNER JOIN
Table_JuniorRecruiter ON Table_Applicant.Junior_Recruiter_ID = Table_JuniorRecruiter.Junior_Recruiter_ID;
The brackets you have round the first table and its first inner join give a syntax error. Between the ( and the ) needs to be a complete SELECT statement, and you start off with a table name, which no valid SELECT statement will do.
Now I don't actually know what you're trying to do, but this will be valid SQL:
SELECT
Applicant_ID, Complete_Name, Date_of_Birth, Date_of_Application, Gender,
City_Address, Position_Applied, Civil_Status, Age, Educational_Attainment,
Table_JuniorRecruiter.Junior_Recruiter_ID, Junior_Recruiter_Name, Exam_Remarks,
Table_Exam.Exam_Number
FROM
Table_Applicant
INNER JOIN
Table_Exam ON Table_Applicant.Exam_Number = Table_Exam.Exam_Number
INNER JOIN Table_JuniorRecruiter
ON Table_Applicant.Junior_Recruiter_ID
= Table_JuniorRecruiter.Junior_Recruiter_ID
Here I've just taken out the ( and the ). It should be valid SQL (provided the table and column names are correct) but it might not be the actual query you want.
However, I can't see what you'd gain by making the table_applicant and table_exam join a nested subquery: doing that looks totally un-necessary.