I have 2 custom object.
1 - namespace__object1__c
2 - namespace__object2__c
I have lookup relationship in custom object namespace__object2__c.
Now i want to query id record from object2 where object1 id = (provided parameter)
String s = 'a6T3k0000LMJcEAO';
string query = 'select ID, (select ID from namespace__object1__c where ID = :s ) from namespace__object2__c';
SObject rObject = database.query(query);
system.debug(rObject);
object2 has lookup to object1, right? What's the field name?
SELECT Id, Name
FROM namespace__object2__c
WHERE namespace__object1__c = 'a6T3k0000LMJcEAO'
should work. Put the right field name in (lookup field typically is but doesn't have to be identical).
Some other things you can do with this (but let's use std. objects in example)
SELECT Id, Name
FROM Contact
WHERE AccountId = '001...'
SELECT Id, Name, Account.Name
FROM Contact
WHERE Account.Name LIKE 'Acme%'
And even
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE LastName = 'Smith')
Related
In BigQuery, How can I turn many columns into a RECORD or Array of Key Value pairs
e.g.
Source Table
id
Name
DOB
Sex
1
Fred
01.01.2001
M
Destination Table
Id
Name
Key
Value
1
Fred
DOB
01.01.2001
Sex
M
I've tried a few things but cant get there, is there a nice way of doing it?
I've tried a few things but cant get there, is there a nice way of doing it?
Not sure what exactly was /could be an issue here as it is as simple/straightforward as below
select id, Name,
[struct<key string, value string>('DOB', DOB),('Sex', Sex)] info
from `project.dataset.table`
with output
Meantime, usually the issue comes when you don't know those columns names in advance and want to have generic approach - in this case you can use below approach where column names DOB and Sex are not being used
select id, Name,
array(
select as struct
split(replace(kv, '"', ''),':')[offset(0)] key,
split(replace(kv, '"', ''),':')[offset(1)] value,
from unnest(split(trim(to_json_string((select as struct * except (id, name) from unnest([t]))), '{}'))) kv
) info
from `project.dataset.table` t
with exact same result/output
Here you go with a solution:-
WITH `proj.dataset.tbl` AS
(SELECT '1' AS id, 'Fred' AS Name, '2020-12-07' AS DOB, 'M' as Sex
)
SELECT id, Name,
[struct('DOB' as key, cast (DOB as string) as value ),
struct('Sex' as key, Sex as value)
] as key_values
FROM `proj.dataset.tbl`
Output will be as :-
Here is my situation: I have two tables, table A has columns:
ID,
Name,
ClassYear,
Classmonth
ID is the primary key no duplicates.
Table b has these columns:
ID,
addresstype
addline1
addline2
country,
city,
state,
zip
ID is not unique in table B but it is how you link back to table A.
If you have more than one address e.g. Home, school then you have more than on record in table b.
My task is to select everyone from table A that has a class year that is >= 2019 and everyone that has a class year = 2018 as long as the class month is >=5
I got that no problem.
Where it gets confusing to me is now that I have this list of people from table A I need to query table b and I only want to pull those who have both a home and school address types and the addresses are identical e.g. line 1, line 2, country, city, state, zip are identical.
I would greatly appreciate some insight.
You could group by the address' details and count the number of distinct types it has:
SELECT *
FROM table1
WHERE id IN (SELECT id
FROM table2
WHERE addresstype IN ('home', 'school')
GROUP BY id, addline1, addline2, country, city, state, zip
HAVING COUNT(DISTINCT addresstype) = 2)
SELECT
DISTINCT
student.ID
, student.Name
, student.ClassYear
, student.ClassMonth
FROM
TableA AS student
INNER JOIN TableB AS homeAddress ON
student.ID = homeAddress.ID
AND homeAddress.addressType = 'Home'
INNER JOIN TableB AS schoolAddress ON
student.ID = schoolAddress.ID
AND schoolAddress.addressType = 'School'
AND homeAddress.line1 = schoolAddress.line1
AND homeAddress.line2 = schoolAddress.line2
AND homeAddress.country = schoolAddress.country
AND homeAddress.city = schoolAddress.city
AND homeAddress.state = schoolAddress.state
AND homeAddress.zip = schoolAddress.zip
WHERE
student.classYear >= 2019
OR (student.ClassYear = 2018 AND student.classMonth >= 5)
;
I am trying to generate unique Login username for each users in my system.
What I have done so far is:
Select p.FirstName+P.LastName + p.PersonId from person As P
Here 1255 is Primary Key. The Output is like JamesHarley1255 ,
However I don't want to use the Primarykey. What are other
alternatives.There will be numerous Duplicate Records too.
Lets say I need a function that generates a unique number everytime between 1 to n numbers. And somehow I need to produce output like JamesHarley125
Try this,
Select p.FirstName+P.LastName +CAST(ROW_NUMBER() OVER (ORDER BY p.FirstName) AS VARCHAR(20))
from person As P
If you want to get one unique column against each record without using primary key column, I think you can use Row Number function. Query below should work in this case
Select p.FirstName+P.LastName + CAST((row_number() OVER ( PARTITION BY p.FirstName ORDER BY p.FirstName)) AS varchar(100)) from person As P
You can create an column with incremental integers using identity property and you can concatenate the same with the first name and last name. So that each row will be unique.
Select p.FirstName+P.LastName + P.Id from person As P
Here column P.Id can declared as below in the table definition. This will start with value '1' and will be incremented in the scale of '1'. Identity(seed, increment)
id int IDENTITY(1,1)
Building off the previous responses, this generates usernames without the numbers where possible, and then only adds numbers to make the usernames unique where actually required. I know this isn't the exact way you are generating your usernames, but this is how I decided to generate mine. I just changed the table names to match yours.
with Usernames(PersonId, Username) as
(
select PersonId,
left(Firstname, 1) + Middlename + Lastname as Username
from Person
),
NumberedUserNames(PersonId, Username, Number) as
(
select PersonId,
Username,
ROW_NUMBER() OVER (PARTITION BY Username ORDER BY Username) as Number
from Usernames
),
UniqueUsernames(PersonId, UniqueUsername) AS
(
select PersonId,
case when Number = 1 then UserName
else UserName + CAST(Number-1 as VarChar(20))
End as UniqueUsername
from NumberedUserNames
)
select PersonId,
UniqueUsername
from UniqueUsernames;
I have two tables, Customer and RegisteredCustomer.
Customer table has the first and last name of customers including the family members stored against each Residentid.
The RegisteredCustomer has the CustomerType as 1 being primary and 2 being FamilyMembers.
I want to select both the primary and Familymember displayed side by side.
Select FirstName, LastName
from Customer
Inner Join RegisteredCustomers on Customer.Customerid = RegisteredCustomer.Customerid
and CustomerType = 1
How can I achieve it?
Thanks
Try it like this:
Select a.Customerid,FirstName, LastName,b.CustomerType from
(Select Customerid,FirstName, LastName from Customer) as a
left join
(select Customerid,cusdescription,CustomerType from RegisteredCustomers)as b
on a.Customerid = b.Customerid where CustomerType = 1
Hope it could help.
I'm trying to create a command to copy the details of client memberships from one database to another with identical structure. I've pared it down to the bare essentials for the purposes of the question so the four items to copy are the expiry date, the subscription ID, the client ID and the item ID (which is the service which comprises the subscription).
The clients have a common GUID in both bases. The subscription ID is a unique long int which should be the same in both bases and the expiry date is just a date. So far, so easy. The tricky part is that the item_id is not necessarily the same in each database. I need to map from one to the the other with a where statement, which I know how to do.
My problem is that I need to select from the destination database's own ITEM table (item_0) in order to get and insert the correct item_id and when I do this I get thousands of duplicate rows returned. I assume I need to use a join to avoid this but as I have nothing meaningful to join item_0 to I can't get any results.
insert into DestDB..subscription (expiry_date,id,client_id,item_id)
select
sub_1.expiry_date,
sub_1.id,
cli_0.id as client_id,
item_0.id as item_id,
from SourceDB..subscription sub_1,
DestDB..item item_0,
DestDB..client cli_0
inner join SourceDB..client cli_1
on cli_1.[guid] = cli_0.[guid]
where sub_1.id not in (select id from DestDB..subscription)
and item_0.id =
(select id from DestDB..collectiondetails
where service_ID =
(select id from DestDB..service s_0 where s_0.code =
(select code from SourceDB..service s_1 where s_1.id =
(select service_ID from Source..collectiondetails item_1 where item_1.id = sub_1.item_id)))
and collection_ID =
(select id from DestDB..collection col_0
where col_0.code =
(select code from SourceDB..collection col_1 where col_1.id =
(select collection_ID from SourceDB..collectiondetails item_1 where item_1.id = sub_1.collection_ID)))
)
I am afraid the updated question is even more confusing. Is this Select in Where clause guaranteed to return one record only or should it be in instead of =?
If there is no rule to identify a particular DestDB..item from the list of matching then the top one should do as well. It would still seem that item_0 can be omitted altogether:
insert into DestDB..subscription (expiry_date,id,client_id,item_id)
select
sub_1.expiry_date,
sub_1.id,
cli_0.id as client_id,
(select Top 1 id from DestDB..collectiondetails --<- Limit to top 1 only
where service_ID =
(select id from DestDB..service s_0 where s_0.code =
(select code from SourceDB..service s_1 where s_1.id =
(select service_ID from SourceDB..collectiondetails item_1 where item_1.id = sub_1.item_id)))
and collection_ID =
(select id from DestDB..collection col_0
where col_0.code =
(select code from SourceDB..collection col_1 where col_1.id =
(select collection_ID from SourceDB..collectiondetails item_1 where item_1.id = sub_1.collection_ID)))
) as item_id,
from SourceDB..subscription sub_1,
DestDB..client cli_0
inner join SourceDB..client cli_1
on cli_1.[guid] = cli_0.[guid]
where sub_1.id not in (select id from DestDB..subscription)
Please note: if DestDB..item is empty the question example statement would not insert anything, but this answer one - would with item_id set to NULL.
I personally would try splitting this task into two separate statements in one transaction:
Insert into target table with NULL item_id.
Update target table with new item_id where item_id is NULL.
(optional) Delete unwanted records where appropriate item_id could not be found.