I am very new to SQL.. I have two tables.. contacts and addresses.. trying to see where the contact has multiple addresses that are marked as home.
I want to show information from both tables where the ra.cv__Contact__c (address) is the same for multiple records and the records say Address Type is home. When I remove my count function line I do see all the records that have a address marked as home, but when I put in
FROM dbo.cv__Related_Address_Detail__c ra LEFT JOIN dbo.Contact c on c.Id=ra.cv__Contact__c
WHERE ra.cv__Contact__c=ra.cv__Contact__c AND ra.cv__Address_Type__c='home'
HAVING COUNT (ra.cv__Contact__c)>1
ORDER BY ra.cv__Contact__c;``
I get this error
Column 'dbo.cv__Related_Address_Detail__c.cv__Contact__c' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
and when I add group by
FROM dbo.cv__Related_Address_Detail__c ra LEFT JOIN dbo.Contact c on c.Id=ra.cv__Contact__c
WHERE ra.cv__Contact__c=ra.cv__Contact__c AND ra.cv__Address_Type__c='home'
GROUP BY ra.cv__Contact__c
HAVING COUNT (ra.cv__Contact__c)>1
ORDER BY ra.cv__Contact__c;
I get
Column 'dbo.cv__Related_Address_Detail__c.Contact_VIS_Number__c' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 145, Level 15, State 1, Line 514
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
Help
So it took a few different ways but I figured out that the problem is simply that i am trying to output too many fields that are not being aggregated..
so i bracketed my fields and did another inner join to get the count
SELECT c.id, COUNT(ra.id) 'Count'
FROM dbo.cv__Related_Address_Detail__c ra JOIN dbo.Contact c on
c.Id=ra.cv__Contact__c
WHERE ra.cv__Address_Type__c='Home'
GROUP BY c.Id
Having COUNT(ra.id)>1
)prime
ON c.id=prime.Id
Related
I am using the below query and it gives error that "Selected non-aggregate values must be part of the associated group. SELECT Command Failed."
SELECT TOP 100 X_ISP_AFF_ADDR_SEQ, CAST(COUNT(*) AS BIGINT) AS COUNT_ROW FROM S_CONTACT WHERE X_ISP_AFF_ADDR_SEQ NOT LIKE '%[a-zA-Z]%';
I changed the above query as written below but the error still persists.
SELECT TOP 100 X_ISP_AFF_ADDR_SEQ, CAST(COUNT(X_ISP_AFF_ADDR_SEQ) AS BIGINT) AS COUNT_ROW FROM S_CONTACT WHERE X_ISP_AFF_ADDR_SEQ NOT LIKE '%[a-zA-Z]%';
You presumably are missing a GROUP BY clause here:
SELECT TOP 100
X_ISP_AFF_ADDR_SEQ,
CAST(COUNT(*) AS BIGINT) AS COUNT_ROW
FROM S_CONTACT
WHERE
X_ISP_AFF_ADDR_SEQ NOT LIKE '%[a-zA-Z]%'
GROUP BY
X_ISP_AFF_ADDR_SEQ;
The exact error you were seeing with your original query has to do with that selecting X_ISP_AFF_ADDR_SEQ instructs Teradata to return a value for each record in the table, whereas COUNT() returns a value over the entire table. It is not possible (in general) to mix aggregates and non aggregates in a select clause.
I have a bill of material file that I am trying to reduce to only the unique parts, and related data for the line. The problem I'm running into is multiple instances of a part number due to variations in the formatting or language in the part name from the system/s that a third party pulls the data from.
pn123 part_name
pn123 Part-name
pn123 Part name
pn123 German name
All other fields I select are equal, how do I limit this in the where clause to just one instance of the above for all different part numbers? Is there an equivalent to MAX() in a text string?
I am working around the issue in excel, by deleting the dupes.
select distinct
adhoc.ats_esh.Customs_Entry_Num
[VIN]as [Qlickview VIN]
,[Build_Date]
,[BOM_Level]
,[9802].[Supplier]
,[Part_number]
,[Part_Name] *******THIS IS THE PROBLEM FIELD*******
,[Unit_Price]
,[Usage]
,[Extended_Price]
from
adhoc.IMFM_9802_EU_AP [9802] inner join ADHOC.ATS_ESL
ON [9802].VIN = ADHOC.ATS_ESL.Part_Num
inner join adhoc.ATS_ESH
ON ADHOC.ATS_ESH.Trans_SK = ADHOC.ATS_ESL.Trans_SK
where
adhoc.ats_esh.importer ='ACME_CO'
and adhoc.ATS_ESH.ENTRY_SUMMARY_DATE >= '2/01/2018'
And adhoc.ATS_ESH.ENTRY_SUMMARY_DATE < '3/01/2018'
AND adhoc.ats_esl.Supplier in('supplier1','supplier2','supplier3')
--and adhoc.ats_esl.Part_Num like '%ABC%'
--and [BOM_Level] = '1' --**** use MAX()
The right way to do this is to have a table with part name and number where part number is a unique key. This way you join on Part_number and get a unique Part_name. You can also use Max(Part_name) if you use Group by Part_number but this will require you to rework your query a little bit.
This is similar to Merge existing records in neo4j, remove duplicates, keep relationships, except that the nodes I want to merge have 0-2 relationships I want to keep.
Take the graph generated by:
create (:Person {name:"Bob"})-[:RELATED_TO]->(:Person {name:"Jane"})-[:FRIENDS_WITH]->(:Person {name:"Tim"})<-[:FRIENDS_WITH]-(:Person {name:"Jane"}),
(:Person {name:"Sally"})-[:RELATED_TO]->(:Person {name:"Jane"})
I want to merge the duplicate Jane nodes, preserving the RELATED_TO and FRIENDS_WITH relationships, removing the duplicates.
From the other question I can get as far as:
match (p:Person {name:"Jane"})
with p.name as name, collect(p) as ps, count(*) as pcount
where pcount > 1
with head(ps) as first, tail(ps) as rest
unwind rest as to_delete
return to_delete
But I can't seem to get the matches and/or optional matches correct for merging. I tried chaining optional matches and doing the merge in one statement and neo4j gives me a Statement.ExecutionFailure with no additional message. I tried breaking out the merges into each match and ended up with "other node is null". Thoughts?
The following query is working. On a side note, for this kind of refactoring I would love the day when it would be possible to set a relationship type with a dynamic variable :
MATCH (n:Person { name:"Jane" })
WITH collect(n) AS janes
WITH head(janes) AS superJane, tail(janes) AS badJanes
UNWIND badJanes AS badGirl
OPTIONAL MATCH (badGirl)-[r:FRIENDS_WITH]->(other)
OPTIONAL MATCH (badGirl)<-[r2:RELATED_TO]-(other2)
DELETE r, r2, badGirl
WITH superJane, collect(other) AS friends, collect(other2) AS related
FOREACH (x IN friends | MERGE (superJane)-[:FRIENDS_WITH]->(x))
FOREACH (x IN related | MERGE (x)-[:RELATED_TO]->(superJane))
Result :
I need some guidance about making two different but related queries in Access:
Query 1: Table 1 joins on matches in Table 2 using two fields and using OR (i.e. can match on one field or the other).
Query 2: Table 1 joins on non-matches (excludes) in Table 2 using two fields and using OR (i.e. can match on one field or the other)
1: note the parenthesis (you could also do this in join but my preference is in the where statement) This is approximate code, the syntax may be slightly off for Access SQL but it should help point you in the right direction.
WHERE ((table1.fieldA = table2.fieldB
AND table1.fieldA = table2.fieldC) OR
table1.fieldA = table2.fieldD)
2:
FROM table1
LEFT JOIN Table2
ON (table1.fieldA = table2.fieldB
AND table1.fieldA = table2.fieldC)
OR table1.fieldA = table2.fieldD
WHERE (IS NULL table2.fieldB AND
IS NULL table2.fieldC)
OR IS NULL table2.fieldD
I want to execute a SELECT query on a database table that has 6 key fields, let's assume they are keyA, keyB, ..., keyF.
As input parameters to my ABAP function module I do receive an internal table with exactly that structure of the key fields, each entry in that internal table therefore corresponds to one tuple in the database table.
Thus I simply need to select all tuples from the database table that correspond to the entries in my internal table.
Furthermore, I want to aggregate an amount column in that database table in exactly the same query.
In pseudo SQL the query would look as follows:
SELECT SUM(amount) FROM table WHERE (keyA, keyB, keyC, keyD, keyE, keyF) IN {internal table}.
However, this representation is not possible in ABAP OpenSQL.
Only one column (such as keyA) is allowed to state, not a composite key. Furthermore I can only use 'selection tables' (those with SIGN, OPTIOn, LOW, HIGH) after they keyword IN.
Using FOR ALL ENTRIES seems feasible, however in this case I cannot use SUM since aggregation is not allowed in the same query.
Any suggestions?
For selecting records for each entry of an internal table, normally the for all entries idiom in ABAP Open SQL is your friend. In your case, you have the additional requirement to aggregate a sum. Unfortunately, the result set of a SELECT statement that works with for all entries is not allowed to use aggregate functions. In my eyes, the best way in this case is to compute the sum from the result set in the ABAP layer. The following example works in my system (note in passing: using the new ABAP language features that came with 7.40, you could considerably shorten the whole code).
report zz_ztmp_test.
start-of-selection.
perform test.
* Database table ZTMP_TEST :
* ID - key field - type CHAR10
* VALUE - no key field - type INT4
* Content: 'A' 10, 'B' 20, 'C' 30, 'D' 40, 'E' 50
types: ty_entries type standard table of ztmp_test.
* ---
form test.
data: lv_sum type i,
lt_result type ty_entries,
lt_keys type ty_entries.
perform fill_keys changing lt_keys.
if lt_keys is not initial.
select * into table lt_result
from ztmp_test
for all entries in lt_keys
where id = lt_keys-id.
endif.
perform get_sum using lt_result
changing lv_sum.
write: / lv_sum.
endform.
form fill_keys changing ct_keys type ty_entries.
append :
'A' to ct_keys,
'C' to ct_keys,
'E' to ct_keys.
endform.
form get_sum using it_entries type ty_entries
changing value(ev_sum) type i.
field-symbols: <ls_test> type ztmp_test.
clear ev_sum.
loop at it_entries assigning <ls_test>.
add <ls_test>-value to ev_sum.
endloop.
endform.
I would use FOR ALL ENTRIES to fetch all the related rows, then LOOP round the resulting table and add up the relevant field into a total. If you have ABAP 740 or later, you can use REDUCE operator to avoid having to loop round the table manually:
DATA(total) = REDUCE i( INIT sum = 0
FOR wa IN itab NEXT sum = sum + wa-field ).
One possible approach is simultaneous summarizing inside SELECT loop using statement SELECT...ENDSELECT statement.
Sample with calculating all order lines/quantities for the plant:
TYPES: BEGIN OF ls_collect,
werks TYPE t001w-werks,
menge TYPE ekpo-menge,
END OF ls_collect.
DATA: lt_collect TYPE TABLE OF ls_collect.
SELECT werks UP TO 100 ROWS
FROM t001w
INTO TABLE #DATA(lt_werks).
SELECT werks, menge
FROM ekpo
INTO #DATA(order)
FOR ALL ENTRIES IN #lt_werks
WHERE werks = #lt_werks-werks.
COLLECT order INTO lt_collect.
ENDSELECT.
The sample has no business sense and placed here just for educational purpose.
Another more robust and modern approach is CTE (Common Table Expressions) available since ABAP 751 version. This technique is specially intended among others for total/subtotal tasks:
WITH
+plants AS (
SELECT werks UP TO 100 ROWS
FROM t011w ),
+orders_by_plant AS (
SELECT SUM( menge )
FROM ekpo AS e
INNER JOIN +plants AS m
ON e~werks = m~werks
GROUP BY werks )
SELECT werks, menge
FROM +orders_by_plant
INTO TABLE #DATA(lt_sums)
ORDER BY werks.
cl_demo_output=>display( lt_sums ).
The first table expression +material is your internal table, the second +orders_by_mat quantities totals selected by the above materials and the last query is the final output query.