SQL Function Get Column By Reference - sql

Let's say there are 3 tables: Genders, Countries and Users. Users has among others a column named Gender and also a column named Country.
I want to add a new entry to Users and select one of the columns Male/Female {M, F} and a country from the rows of Countries dynamically just for testing purposes.
insert into dbo.[Users] (Gender, UserName, Country)
select Genders.Male, 'newbie', Countries.(the one which matches column CountryId) FROM Genders, Countries
I want to achieve this: 'M', 'newbie', MyCountry
After applying the suggestion from 'zip' I get the result 2 rows affected, same number as the external tables I'm referencing. The Query added 2 rows, so I guess I am missing the WHERE conditions.
The Genders Table is meant as a Property and will have only one row that I manually added.
Table Genders; 1 row
Male : uniqueidentifier
Female : uniqueidentifier
Countries is a table with many rows, so I want to select one matching the criteria of one of it's column values, say the value of column CountryId.

You can get a random value using:
insert into dbo.[Users] (Gender, UserName)
select top (1) g.Male, 'newbie'
from Genders.Male
order by newid();

I figuored the solution out. Thank you all who responded for pointing me in the right direction.
INSERT INTO dbo.[Users] (Gender, UserName, Country)
SELECT Genders.Male, 'newbie', Countries.CountryId
FROM Genders, Countries
WHERE Countries.ISO2 = '##'
'##' = 2 letter ISO of country.
Explanation:
1. INSERT INTO dbo.[Users] = Add a new row to Table "Users"
2. (Gender, UserName, Country) = Includes the columns in table "Users". If a column is not specified and it had a property of not allowing Nulls, an exception would be thrown!
3. FROM Genders, Countries = Include the external tables associated to look for
4. WHERE Countries.ISO2 = '##' = This condition allows you to precisely select which column of which row you seek. So I searched for a certain row where a column named ISO2 had a value '##' and looked then for the CountryId value in the same row (entry). There may be cases when multiple rows have identical value so you would have to further specify the conditions by using AND or OR oeprators.
When a table does not contain more than 1 row, I should not have to apply WHERE Conditions. It will select the default one existing. But because the Countries Table had multiple items (3 Rows), leaving the WHERE clause out, caused to add 3 times the same User, with each row having a distinct CountryId!

Related

Insert multiple columns into a mapped 1-1 single column

I have the following setup in SQL Server 2016. I want to insert into table B name, surname, address into there respective columns, but from the 3 columns in View A for employment, I want to insert a single row for each person based on their Employment into Employment Status column in Table B, What is the best way to do this?
View A
Name (String)
Surname (Sring)
Address (String)
Employed (boolean)
Non-Employed (boolean)
Retired (boolean)
Table B
Name (String)
Surname (Sring)
Address (String)
Employed Status (String)
Although you have three flags that seem exclusive, I see no reason to think that they actually are (unless you have some sort of validation).
So, I would concatenate the statuses together:
insert into b (name, surname, address, employed_status)
select name, surname, address,
stuff(concat(case when employeed = 1 then ', employed' else '' end,
case when non_employeed = 1 then ',non_employed' else '' end,
case when retired = 1 then ',retired' else '' end
), 1, 1, ''
)
from a;
Note: SQL Server does not have a boolean type, so I assume you are using 0/1 encoding for the columns.
I would take a step back and create another table called EmploymentState, into which I would add three rows "1 - Employed", "2 - Unemployed", "3 - Retired". Then add a foreign key to that table from Table A and Table B.
Unless of course, a single person can be in more than one state...in which case you need an intersection table. See https://www.bing.com/search?q=sql+intersection+table&qs=n&form=QBRE&sp=-1&ghc=1&pq=sql+intersection+tab&sc=0-20&sk=&cvid=153E23C3D25F461E89F71E106FBF7D66

Converting multiple rows into single row with multiple columns

I have a table that has multiple rows for a distinct CARD_ID listing different roles assigned to that CARD_ID. I'd like to have a query that creates a single row for each distinct CARD_ID that has multiple columns listing the different roles. See image for example of current table. Duplicates are highlighted.
So, I'd like one row for CARD_IDs 1-10, with columns in each row for Cardholder, Reconciler, and Approver.
If a particular CARD_ID doesn't have one of those roles, I'm ok with that field being null or having some other type of indicator.
One method i conditional aggregation:
select card_id,
max(iif(role = 'Reconciler', col, NULL)) as reconciler_col,
max(iif(role = 'Approver', col, NULL)) as approver_col,
max(iif(role = 'Cardholder', col, NULL)) as cardholder_col
from t
group by card_id;
col is a column that you want to pivot. You can add more than one column, just by adding more max(iif . . .) to the select.

Count only a specific subset of elements in a Postgres DB

I have a table with some identifiers that repeat themselves like
id
-------
djkfgh
kdfjhw
efkujh
dfsggs
djkfgh
djkfgh
efkujh
I also have a list of id's of interest, say ["djkfgh","dfsggs"]. I would like to count only those values that appear in the list, rather than all the distinct values of the column.
Select count(id) from table where id IN(subset);

SQL using where contains to return rows based on the content of another table

I need some help:
I have a table called Countries, which has a column named Town and a column named Country.
Then I have table named Stores, which has several columns (it is a very badly set up table) but the ones that are important are the columns named Address1 and Address2.
I want to return all of the rows in Stores where Address1 and Address2 contains the towns in the Countries table.
I have a feeling this is a simple solution but I just can't see it.
It would help if maybe you could use WHERE CONTAINS but in your parameters search in another table's column?
e.g.
SELECT *
FROM Stores
WHERE CONTAINS (Address1, 'Select Towns from Countries')
but obviously that is not possible, is there a simple solution for this?
You're close
SELECT * FROM Stores s
WHERE EXISTS (
SELECT * FROM Countries
WHERE CONTAINS(s.Address1, Town) OR CONTAINS(s.Address2, Town)
)
This would be my first attempt:
select * from stores s
where
exists
(
select 1 from countries c
where s.Address1 + s.Address2 like '%'+c.Town+'%'
)
Edit: Ooops just saw that you want the 'CONTAINS' clause. Then take Paul's solution

Need a count query in access but one column only needs unique values

I have a table 'tblBaseResults' setup like this
Column 1 = Name
Column 2 = Activity
The Activity column is supposed to be unique. However there are multiple Name fields. So im not sure how to get the Activity column to unique values and keep just one value from Name.
I would prefer to just keep the values from name that DO NOT have any '?' characters.
The current Count query i have works great. However i need only ONE of the Name fields to carry over with it
SELECT tblBaseResults.Activity, Count(tblBaseResults.Activity) AS CountOfActivity INTO tblCountResults
FROM tblBaseResults
GROUP BY DISTINCT tblBaseResults.Activity;
In Excel if i do a VLookup i get what i need, but want to do it in access.
INSERT INTO tblCountResults (Activity, Name, CountOfActivity)
SELECT Activity, min(Name), Count(tblBaseResults.Activity)
FROM tblBaseResults
WHERE instr(Name, '?') = 0
GROUP BY Activity