SQL Repetition, how to avoid in query? - sql

I'm trying to get the names and the addresses that are stored in the table but getting data repetition. I dont know how to avoid it as im a newbie to this field. here's some pictures of the commands and results.
Commands:
Results:
Owner Table:
Addresses Table:
Please help me out :(
P.S. They are all dummy data.

You need to do a join between the two tables owners and addresses using column in tables that referenece each other.
SELECT firstname,lastname,addressline_1
FROM owners o
JOIN addresses a
ON o.colName=a.colName
Your query is performing cartesian product between the two tables which is giving all rows for table address for each row in table owners.
You would have avoided getting meaningless rows had you used recommended ANSI SQL syntax of performing join using ON clause rather than WHERE clause . Although you haven't specified condition for joining between the tables still old syntax of joining using WHERE clause got executed successfully but would have thrown error in case of using ON clause.
See this thread for detailed discussion ON vs WHERE
EDIT
As per your schema of tables the query would be
SELECT firstname,lastname,addressline_1
FROM owners o
JOIN addresses a
ON o.ownerid=a.owners_ownerid

you have to add where clause to your query:-
SELECT OWNERS.first_name, OWNERS.last_name, ADDRESSES.address_line1
FROM OWNERS, ADDRESSES
WHERE OWNERS.ownerid = ADDRESSES.owners_ownerid
or you can use join
SELECT OWNERS.first_name, OWNERS.last_name, ADDRESSES.address_line1
FROM OWNERS
JOIN ADDRESSES
ON OWNERS.ownerid = ADDRESSES.owners_ownerid

Related

Best way to "SELECT *" from multiple tabs in sql without duplicate?

I am trying to retrieve every data stored in 2 tabs from my database through a SELECT statement.
The problem is there are a lot of columns in each tab and manually selecting each column would be a pain in the ass.
So naturally I thought about using a join :
select * from equipment
join data
on equipment.id = data.equipmentId
The problem is I am getting the equipment ID 2 times in the result.
I thought that maybe some specific join could help me filter out the duplicate key, but I can't manage to find a way...
Is there any way to filter out the foreign key or is there a better way to do the whole thing (I would rather not have to post process the data to manually remove those duplicate columns)?
You can use USING clause.
"The USING clause specifies which columns to test for equality when
two tables are joined. It can be used instead of an ON clause in the
JOIN operations that have an explicit join clause."
select *
from test
join test2 using(id)
Here is a demo
You can also use NATURAL JOIN
select *
from test
natural join test2;

JOIN is not allowed for pool tables, cluster tables, and projection views: ‘BSEG’

I am trying to select some fields of the table BKPF by using the inner join of the tables BSEG and KNBK, into another table. The code for this is as below:
SELECT k~bukrs, k~belnr, k~budat, k~gjahr, s~buzei,
s~kunnr, i~banks, i~bankl, i~bankn
FROM bkpf AS k
INNER JOIN bseg AS s "Error
ON s~bukrs = k~bukrs AND
s~belnr = k~belnr AND
s~gjahr = k~gjahr
INNER JOIN knbk AS i
ON i~kunnr = s~kunnr
INTO TABLE #DATA(lt_data_knbk)
WHERE k~bukrs IN #so_bukrs
AND k~budat IN #so_budat
AND k~blart IN #so_blart.
The last three where conditions are select options. The error that I got from activating the program is from the bold line, where the error message is: JOIN is not allowed for pool tables, cluster tables, and projection views: ‘BSEG’.
May anyone know, how can I fix this problem?
Thank you in advance for your kind help!
BSEG is a cluster table, it cannot be indcuded in JOINs (if you does not use a HANA DB, but the error message says, it does not). To overcome this, the table has to be selected in a separate step. In your case this would actually mean three separate SELECTs, as BKPF cannot be JOINed with KNBK (no common field(s)).
So in this case, it is better to use the transparent tables for customer postings (BSID and BSAD), these can be included in a JOIN. The only disadvantage is, that the postings are separated:
BSID: customer open postings
BSAD: customer cleared postings
so two separate SELECTs will be necessary (depending on the exact need, but this was stated in the original question).
In this case you can forget BKPF, as all fields you actually use in your code, are in BSID/BSAD.
SELECT bsid~bukrs, bsid~belnr, bsid~budat, bsid~gjahr, bsid~buzei,
bsid~kunnr, knbk~banks, knbk~bankl, knbk~bankn
FROM bsid
INNER JOIN knbk
ON bsid~kunnr EQ knbk~kunnr
INTO TABLE #DATA(lt_bsid_knbk)
WHERE bsid~bukrs IN #s_bukrs
AND bsid~budat IN #s_budat
AND bsid~blart IN #s_blart.
As told this has to be repeated, BSID has to be replaced by BSAD.
You can join different type of tables on Hana based systems. But you can't do that for old systems. You need to use multiple separate query and populate needed values.

Access SQL Syntax error: missing operator

I am trying to convert a T-SQL query to MS Access SQL and getting a syntax error that I am struggling to find. My MS Access SQL query looks like this:
INSERT INTO IndvRFM_PreSort (CustNum, IndvID, IndvRScore, IndRecency, IndvFreq, IndvMonVal )
SELECT
IndvMast.CustNum, IndvMast.IndvID, IndvMast.IndvRScore,
IndvMast.IndRecency, IndvMast.IndvFreq, IndvMast.IndvMonVal
FROM
IndvMast
INNER JOIN
OHdrMast ON IndvMast.IndvID = OHdrMast.IndvID
INNER JOIN
MyParameterSettings on 1=1].ProdClass
INNER JOIN
[SalesTerritoryFilter_Check all that apply] ON IndvMast.SalesTerr = [SalesTerritoryFilter_Check all that apply].SalesTerr
WHERE
(((OHdrMast.OrdDate) >= [MyParameterSettings].[RFM_StartDate]))
GROUP BY
IndvMast.CustNum, IndvMast.IndvID, IndvMast.IndvRScore,
IndvMast.IndRecency, IndvMast.IndvFreq, IndvMast.IndvMonVal,
[CustTypeFilter_Check all that apply].IncludeInRFM,
[ProductClassFilter_Check all that apply].IncludeInRFM,
[SourceCodeFilter_Check all that apply].IncludeInRFM,
IndvMast.FlgDontUse
I have reviewed differences between MS Access SQL and T-SQL at http://rogersaccessblog.blogspot.com/2013/05/what-are-differences-between-access-sql.html and a few other locations but with no luck.
All help is appreciated.
update: I have removed many lines trying to find the syntax error and I am still getting the same error when running just (which runs fine using T-SQL):
SELECT
IndvMast.CustNum, IndvMast.IndvID, IndvMast.IndvRScore,
IndvMast.IndRecency, IndvMast.IndvFreq, IndvMast.IndvMonVal
FROM
IndvMast
INNER JOIN
OHdrMast ON IndvMast.IndvID = OHdrMast.IndvID
INNER JOIN
[My Parameter Settings] ON 1 = 1
There are a number of items in your query that should also have failed in any SQL-compliant database:
You have fields from tables in GROUP BY not referenced in FROM or JOIN clauses.
Number of fields in SELECT query do not match number of fields in INSERT INTO clause.
The MyParameterSettings table is not properly joined with valid ON expression.
Strictly MS Access SQL items:
For more than one join, MS Access SQL requires paired parentheses but even this can get tricky if some tables are joined together and their paired result joins to outer where you get nested joins.
Expressions like ON 1=1 must be used in WHERE clause and for cross join tables as MyParameterSettings appears to be, use comma-separated tables.
For above reasons and more, it is advised for beginners to this SQL dialect to use the Query Design builder providing table diagrams and links (if you have the MS Access GUI .exe of course). Then, once all tables connect graphically with at least one field selected, jump into SQL view for any nuanced scripting logic.
Below is an adjustment to SQL statement to demonstrate the parentheses pairings and for best practices, uses table aliases especially with long table names.
INSERT INTO IndvRFM_PreSort (CustNum, IndvID, IndvRScore, IndRecency, IndvFreq, IndvMonVal)
SELECT
i.CustNum, i.IndvID, i.IndvRScore, i.IndRecency, i.IndvFreq, i.IndvMonVal
FROM
[MyParameterSettings] p, (IndvMast i
INNER JOIN
OHdrMast o ON i.IndvID = o.IndvID)
INNER JOIN
[SalesTerritoryFilter_Check all that apply] s ON i.SalesTerr = s.SalesTerr
WHERE
(o.OrdDate >= p.[RFM_StartDate])
GROUP BY
i.CustNum, i.IndvID, i.IndvRScore, i.IndRecency, i.IndvFreq, i.IndvMonVal
And in your smaller SQL subset, the last table does not need an ON 1=1 condition and may be redundant as well in SQL Server. Simply a comma separate table will suffice if you intend for cross join. The same is done in above example:
SELECT
IndvMast.CustNum, IndvMast.IndvID, IndvMast.IndvRScore,
IndvMast.IndRecency, IndvMast.IndvFreq, IndvMast.IndvMonVal
FROM
[My Parameter Settings], IndvMast
INNER JOIN
OHdrMast ON IndvMast.IndvID = OHdrMast.IndvID
I suppose there are some errors in your query, the first (more important).
Why do you use HAVING clause to add these conditions?
HAVING (((IndvMast.IndRecency)>(date()-7200))
AND (([CustTypeFilter_Check all that apply].IncludeInRFM)=1)
AND (([ProductClassFilter_Check all that apply].IncludeInRFM)=1)
AND (([SourceCodeFilter_Check all that apply].IncludeInRFM)=1)
AND ((IndvMast.FlgDontUse) Is Null))
HAVING usually used about conditions on aggregate functions (COUNT, SUM, MAX, MIN, AVG), for scalar value you must put in WHERE clause.
The second: You have 12 parenthesis opened and 11 closed in HAVING clause

Query returns different results depending on number of tables in FROM

I have several tables in a exercise, lets call them animals, prizes and exhibitions.
When I write following simple query
SELECT animals.name FROM animals;
I get 8 results, all names from the animals table.
However when I write
SELECT animals.name FROM animals, exhibitions, prizes;
I get over six hundred results, all of them names from animals table, just multiple times.
Why is that happening? I specified the column and the table in the SELECT command. I do not want any data from other tables.
Only table animals has a column called name.
Edit: Sorry I asked.
You are performing a union join, which 'multiplies' the tuples in all the tables regardless of whether or not they have common fields. You need to specify a join field in your SQL, else you get this type of join.
when you join several tables you will got the result of all tables, in your example you got not only animal table , you aslo got exhibitions and prizes.
to solve that use a specifque condition example .. where animal.name = exhibitions.place
read more about joins fromt oracle document ( left joins , outer joins) its really helpful

Select query for Multiple tables with one Common Column

a select query for Multiple tables with one Common Column
i have tried something below but not working
Select * from DM_Audit da, DM_APPLICANTS dap , DM_POLICY dp, DM_Names dn,DM_Address ad
where da.fk_applicationID=dap.fk_applicationID and
dap.fk_applicationID=dp.fk_applicationID and
dp.fk_applicationID=dn.fk_applicationID and
dn.fk_applicationID=ad.fk_applicationID
Here fk_applicationID is Common column in all the table
New to the Sql Please Help
The column name may be the same, but does it reference data for the intended records in each table?
If it definitely does, then re-writing the query using joins would be an easier way of checking the links:
Select *
from DM_Audit da
INNER JOIN DM_APPLICANTS dap ON dap.fk_applicationID=da.fk_applicationID
etc........
I would usually have a 'key' table in this situation (i.e. with the most data in it, or one which links to the most other tables which need to be joined) Then it is much easier to join the other tables.
N.B. if not all tables join to the key table, join as many as you can first, then join to the 'joined' tables further down the statement.