Join tables query in SQL Server 2012 - tsql

I have two tables like below:
TableA --> categoryId(pk), categoryParentId, catName
TableB --> empId(pk), categoryId, empName, empDesignation
I want to get all catName with respective categoryId from TableA where categoryId=2 of TableB is equal to categoryParentId=2 of TableA. Please help.
Result:
1002 SE
1003 MD

Something like this?
SELECT DISTINCT catName FROM TABLEA WHERE categoryParentId IN (SELECT DISTINCT categoryID from TABLEB);

I hope this query will fulfill your need
SELECT TABLEA.CATNAME AS CATEGORY
from TABLEB INNER JOIN TABLEA
ON TABLEA.CATEGORYPARENTID = TABLEB.CATEGORYID

Solution with INNER JOIN:
select TableA.catName
from TableA
inner join TableB on TableA.categoryParentId = TableB.categoryId
Using INNER JOIN is the recommended way to use for joining tables (as opposed to SELECT ... FROM TableA, TableB ...)
See:
INNER JOIN ON vs WHERE clause
(this question was actually about MySql, but the answers say that it's the same for SQL Server)
Difference in INNER join and cartesian join in SQL Server
Answering your comment (I assume that you wanted the categoryId from TableA):
select TableA.catName, TableA.categoryId
from TableA
inner join TableB on TableA.categoryParentId = TableB.categoryId
where TableB.categoryId = 2

another method...
SELECT
catname
from
tablea a INNER JOIN
tableb b ON
a.categoryParentID = b.categoryID
group by
catname

This should do the trick
SELECT tableA.catName
FROM tableA, tableB
WHERE tableB.categoryId = table1.categoryParentId
AND tableB.categoryId = 2;
If you want the unique catNames, you can use
SELECT distinct tableA.catName
FROM tableA, tableB
WHERE tableB.categoryId = table1.categoryParentId
AND tableB.categoryId = 2;

Related

power bi get new table filed from linked table

i have 3 linked table:
tableA whith iddocument, total, date
tableB whith iddetail, iddocument, qta, price
tableC whitn idstorychange, iddetail,user_id, typechange, old_value,new_value, date_change
the tables are linked in powerbi:
tableA join tableB (1-N, tableB.iddocument ->tableB.iddocument)
tableB join tableC (1-N, tableB.iddetail->tableC.iddetail)
in need a new table whith fields:
tableA.iddocument,max(tableC.datechange)
where new_value is in some value and group by tableA.iddocument
in T-sql would be:
select
tableA.iddocument,max(tableC.date_change)
from tableA
inner join tableB on tableB.iddocument = tableA.iddocument
inner join tableC on tableC.iddetail = tableB.iddetail
where
tableC.typechange = 'type1' and tableC.new_value in (5,8) and tableC.user_id in (82,87,90,91)
group by tableA.iddocument
i can't create a view in db, i can only read table, i need solve in powerbi.
the table in power bi is imported (not direct query)
thx a lot

If transaction_id is not null join on transaction_id else join on user id - in same join?

I would like to do a single left join from table a onto table b on transaction_id
select a.*, b.*
from tablea a
left join tableb b on b.transaction_id = a.transaction_id
However, there are cases where transaction id on either table is missing, in which case I would like to fall back onto joining on a.user_id = b.user_id. If user_id is also missing then fine, I still want to keep all records from a.
Is there a way I can tell postgres to try joining on one field and if it's missing on either table to then try joining on another field?
Is there a way to do this?
Add a 2nd join to tableb with the condition that the 1st join did not match:
select a.*,
coalesce(b1.col1, b2.col1), coalesce(b1.col2, b2.col2), .....
from tablea a
left join tableb b1 on b1.transaction_id = a.transaction_id
left join tableb b2 on b2.user_id = a.user_id and b1.transaction_id is null

How to find in a many to many relation all the identical values in a column and join the table with other three tables?

I have a many to many relation with three columns, (owner_id,property_id,ownership_perc) and for this table applies (many owners have many properties).
So I would like to find all the owner_id who has many properties (property_id) and connect them with other three tables (Table 1,3,4) in order to get further information for the requested result.
All the tables that I'm using are
Table 1: owner (id_owner,name)
Table 2: owner_property (owner_id,property_id,ownership_perc)
Table 3: property(id_property,building_id)
Table 4: building(id_building,address,region)
So, when I'm trying it like this, the query runs but it returns empty.
SELECT address,region,name
FROM owner_property
JOIN property ON owner_property.property_id = property.id_property
JOIN owner ON owner.id_owner = owner_property.owner_id
JOIN building ON property.building_id=building.id_building
GROUP BY owner_id,address,region,name
HAVING count(owner_id) > 1
ORDER BY owner_id;
Only when I'm trying the code below, it returns the owner_id who has many properties (see image below) but without joining it with the other three tables:
SELECT a.*
FROM owner_property a
JOIN (SELECT owner_id, COUNT(owner_id)
FROM owner_property
GROUP BY owner_id
HAVING COUNT(owner_id)>1) b
ON a.owner_id = b.owner_id
ORDER BY a.owner_id,property_id ASC;
So, is there any suggestion on what I'm doing wrong when I'm joining the tables? Thank you!
This query:
SELECT owner_id
FROM owner_property
GROUP BY owner_id
HAVING COUNT(property_id) > 1
returns all the owner_ids with more than 1 property_ids.
If there is a case of duplicates in the combination of owner_id and property_id then instead of COUNT(property_id) use COUNT(DISTINCT property_id) in the HAVING clause.
So join it to the other tables:
SELECT b.address, b.region, o.name
FROM (
SELECT owner_id
FROM owner_property
GROUP BY owner_id
HAVING COUNT(property_id) > 1
) t
INNER JOIN owner_property op ON op.owner_id = t.owner_id
INNER JOIN property p ON op.property_id = p.id_property
INNER JOIN owner o ON o.id_owner = op.owner_id
INNER JOIN building b ON p.building_id = b.id_building
ORDER BY op.owner_id, op.property_id ASC;
Always qualify the column names with the table name/alias.
You can try to use a correlated subquery that counts the ownerships with EXISTS in the WHERE clause.
SELECT b1.address,
b1.region,
o1.name
FROM owner_property op1
INNER JOIN owner o1
ON o1.id_owner = op1.owner_id
INNER JOIN property p1
ON p1.id_property = op1.property_id
INNER JOIN building b1
ON b1.id_building = p1.building_id
WHERE EXISTS (SELECT ''
FROM owner_property op2
WHERE op2.owner_id = op1.owner_id
HAVING count(*) > 1);

I want to join 3 tables and select 1 coulmn from each table

I have tried using join as follows but it is not working
SELECT distinct(udf.FIELD_NAME),fun.FUNCTION_ID,mo.MODULE AS PRODUCT_MODULE FROM TABLE1 udf
JOIN TABLE2 mo
ON udf.PRODUCT_CODE = mo.PRODUCT_CODE
JOIN TABLE3 fun
ON udf.FIELD_NAME = fun.FIELD_NAME
where (udf.product_code in (select mo.product_code from TABLE2 mo))AND(udf.FIELD_NAME like '%UDF%')AND(udf.FIELD_NAME IN(SELECT fun.FIELD_NAME FROM TABLE3 fun));
I want all the where conditions mentioned here to work
There are some statements in your WHERE clause that mimic the join condition. If you do a join like this
JOIN TABLE2 mo
ON udf.PRODUCT_CODE = mo.PRODUCT_CODE
then there is no need to add the WHERE clause
where (udf.product_code in (select mo.product_code from TABLE2 mo))
because those 2 do the same. Unless you have duplicate rows, the "DISTINCT" clause is not needed either. Your query can be rewritten as:
SELECT
udf.field_name,
fun.function_id,
mo.module AS product_module
FROM
table1 udf
JOIN table2 mo ON udf.product_code = mo.product_code
JOIN table3 fun ON udf.field_name = fun.field_name
WHERE
udf.field_name LIKE '%UDF%';

Using multiple resultsets combined with joins in T-SQL

I'm currently using joins inside my stored procedures for outputting elements from different tables. An aggressive example
select a.*, b.*, c.*, d.*, e.*, f.* from tableA a
join tableB b on a.id = b.foreignid
join tableC c on b.id = c.foreignid
join tableD d on c.id = d.foreignid
join tableE e on d.id = e.foreignid
join tableF f on e.id = f.foreignid
where a.id = 1
It's getting pretty unhandy to work with when mapping the output to entities in my C# code, since I have to maintain a lot of boilerplate code.
Instead I would look into using multiple resultsets, so that I could map each resultset into an object type in code.
But how would I go around achieving this when I my case the different results would all relate to each other? The examples I've been able to find all revolved around selecting from different tables where the data were not related by foreign keys like mine. If I were to ouput my result in multiple resultsets the only thing I can come up with is something like this
select a.* from tableA
where a.id = 1
select b.* from tableB
join tableA a on a.id = b.foreignid
where a.id = 1
select c.* from tableC
join tableB b on b.id = c.foreignid
join tableA on a.id = b.foreginid
where a.id = 1
select d.* from tableD
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1
select e.* from tableE
join tableD d on d.id = e.foreignid
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1
select f.* from tableF
join tableE e on e.id = f.foreignid
join tableD d on d.id = e.foreignid
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1
But this is not cleaner, a lot more ineffecient (I would suppose, since there's alot more join statements)
Is it possible to use multiple resultset in this way I'm trying to? I just don't know how I would write the sql statements in the stored proc without having to do massive joins per resultset as in the example. And with the current solution I get an explosion of columns since I join them all together
You can actually return multiplte resultsets from a single SP and consume them in c#, check this post for instance : http://blogs.msdn.com/b/dditweb/archive/2008/05/06/linq-to-sql-and-multiple-result-sets-in-stored-procedures.aspx
It's a lesser known feature but sounds like what you're asking for. You don't have to join them and return them as a flattend rowset, just get the seperate rowsets and piece them together in memory.
Also you may want to read up on ORM frameworks, that could save you a lot of typing that you coud spend on features if it fits your needs.
https://stackoverflow.com/questions/249550/what-orm-frameworks-for-net-do-you-like-best
Regards GJ