query joining two tables - sql-server

There are my tables:
http://i.imgur.com/dzwokhh.png
I want to write a query that return all info order by categoryId and Name.
For example: I want to return from right table id = 2,15,18 (CategoryId=1)
because in the left table they belong to Java (Id=1)

This should help to solve the problem:
select *
from mytable1
join mytable2 on mytable1.ID=mytable2.CategoryID
order by mytable1.ID ,Name

Related

SQL Server query to get nested child records based on id provided by user

I have SQL Server data in the below format:
In the above table, parentid and sourceid are related, like the parent-child relationship.
in first-row parentid 'A' is sourceid of the second row. User will provide input of sourceid and based on that sourceid, I need to get its related child records.
For example, if the user provides input source id as 'A1', the output should be as shown below:
I tried using self join, but I am not able to get related child records in the table.
select *
from testrecords1 t1
join testrecords1 t2 on t1.parentid = t2.sourceid
where t1.sourceid = 'A1'
This query results in only one record. Please provide corrections / suggestions to achieve the desired output.
You can use Common Table Expression (CTE) for the recursive query.
The query could be written as:
;with MyCTE
as
(
SELECT Parentid, Sourceid from testrecords1 where SourceId = #SourceId
UNION ALL
SELECT t1.Parentid, t1.Sourceid from testrecords1 t1
inner join MyCTE t2 on t1.SourceId = t2.Parentid
)
SELECT * FROM MyCTE
Where #SourceId is the parameter for filter.

Using group by to update multiple records in an update query

I have two tables. Table1 has company data (Company ID, Company Name ...), so single record for each company.
Table2 has information about departments in that company (Department ID, Department Name, Company ID, Company Name ... ). So, second table might have n number of records where same company id is used.
Problem is one of our trigger failed to work properly, and no one noticed till now. So, when Company Name was updated in Table1, it never reflected in Table2.
To correct this, I have to do something like the below query:
Update Table2
Set
[Company Name] = (select [Company Name]
from Table1
where Table2.Company ID = Table1.Company ID)
Group By Table2.Company ID
Basically, I am trying to update all records in Table2 to use the same name as Table1, for each record in Table1.
I am a bit confused about how to create the inner select clause.
P.S. Sorry, it might be a bit confusing. Kindly do let me know how to reword it the best.
Don't need to use group by ...
UPDATE T2
SET [Company Nane] = T1.[Company Nane]
FROM Table1 T1
INNER JOIN Table2 T2
ON T1.[Company ID] = T2.[Company ID]
As other have mentioned: Remove GROUP BY and your query works fine.
GROUP BY is used to produce a result row in a query that is an aggregate of other rows. E.g. one record per company from your department table with the most busy department per company. You cannot update such a result record, for that record does not exist in the table. You can only update table records.
So remove GROUP BY from your query and you have it straight-forward.
Update DepartmentTable
Set [Company Name] =
(
select [Company Name]
from CompanyTable
where CompanyTable.[Company ID] = DepartmentTable.[Company ID]
);

Select value from different tables based on the column value in SQL Server

I have a main table A with the following fields:
Then I have three separate tables, each for Buildings, Classrooms and Offices. All these tables have two columns; ID and Name.
I want to query the table A to get the following result:
How can I do this?
Your data isn't really normalized. Having three separate tables all serving the same lookup is causing you some headache... so I unioned the 3 tables together and created a 'src' column so you could join table A's type and Id back to table B's ID and src. You'd have been better off having one table and non-repeating IDs and a type ID to specify if it's a building classroom or office.
Select *
from A
LEFT JOIN (SELECT 'Building' as src, ID, Name FROM Buildings UNION ALL
SELECT 'Classroom' as src, ID, Name FROM Classrooms UNION ALL
SELECT 'Office' as src, ID, Name FROM Offices) B
on A.Location_Type = B.Src
and A.LocationID = B.ID
I used a left join here in case not all records in A have an associated record in B. However, an inner join should work as well.
Should be doable with the use of a join.
Something along those lines should work:
SELECT tabelA.ID, tabelA.Subject, tabelA.Date, tabelA.locationType, tabelB.location
FROM tabelA INNER JOIN tabelB on tabelA.locationID = tabelB.locationID

Need help on a sql query to get data from multiple tables

I have a couple of tables that have data in them that I am looking to get information from. Here is the rundown....In table 1 I have bunch of columns that I am pulling data from, one of the columns is a user ID (which is a number)that was the last userID to modify a record. In table 2 I want to pull in the name of that user based on the ID that is pulled from the other table (this table has both the userID and the username).
so my final query would have the columns in table 1 as well as the username from table 2 to show that was the user to last edit the record. I assume this has to be done in a nested select statement but for the life of me I cannot come up with the correct syntax.
Can anyone help me out?
Thanks
Jeff
Yes, you need a very basic join that link both tables together.
Select t1.UserID,
t2.UserName
FROM table1 t1 INNER JOIN
table2 t2 ON t1.userid=t2.userid
select t1.*, t2.{username} from table1 as t1
join table2 as t2 on t1.{userId}=t2.{userid};
change {username} with the actual column name of user
similarly {userId} with appropriate column name in tables.
Hope it helps you.
this is standard inner join query, to learn more consider reading: http://www.w3schools.com/sql/

Create table from join SQL Server

I am running the query :
select
[temp_table_excel_insert_for_join].person_id,
[temp_table_excel_insert_for_join].city,
city.city_id
from
temp_table_excel_insert_for_join, city
where
temp_table_excel_insert_for_join.city = city.city
without problem now I want to have all these columns as a new table so I used
create table mytable as
( select
[temp_table_excel_insert_for_join].person_id,
[temp_table_excel_insert_for_join].city,
city.city_id
from
temp_table_excel_insert_for_join, city
where
temp_table_excel_insert_for_join.city=city.city)
but it did not work for me what should I do to make it happen? I don't want to create a view I want to have a table.but I am not familiar if I should do a left join or other things
If your goal is to create a new table mytable with the columns person_id, city, city_id then use the select ... into syntax:
select
[temp_table_excel_insert_for_join].person_id,
[temp_table_excel_insert_for_join].city,
city.city_id
into
mytable
from
temp_table_excel_insert_for_join
inner join
city on temp_table_excel_insert_for_join.city = city.city
Note that this will fail if you run it more than once as the table already would exist and you would have to drop it first.
See the documentation for more information on the into clause
Try this
select [temp_table_excel_insert_for_join].person_id
, [temp_table_excel_insert_for_join].city
,city.city_id
into mytable
from temp_table_excel_insert_for_join inner join city on temp_table_excel_insert_for_join.city=city.city)
Try separating the two operations. First:
CREATE TABLE MyTable ( etc)
Then
INSERT INTO MyTable ( <List of columns to insert> )
SELECT <Columns to insert>
FROM etc
WHERE etc
This works if you remove the brackets after your AS clause - at least in SQL Lite. So you can just write:
CREATE TABLE mytable AS
SELECT
[temp_table_excel_insert_for_join].person_id,
[temp_table_excel_insert_for_join].city,
city.city_id
FROM
temp_table_excel_insert_for_join, city
WHERE
temp_table_excel_insert_for_join.city=city.city;

Resources