Say i have an image :
This signifies that 1 has friends 2,3,4 and 6 is also the friend of 1.
How do i get these ids 2,3,4 and 6 that are friends with 1 using SQL
that depends a bit on which DB you are using - the following will work in MySQL and Oracle and perhaps in MS SQL server (not sure):
SELECT
(CASE WHEN ID1 = 1 THEN ID2 ELSE ID1 END) AS THEFRIENDS
FROM YOURTABLE WHERE
ID2 = 1 OR
ID1 = 1
This one works everywhere but is perhaps less performant:
SELECT ID1 FROM YOURTABLE WHERE ID2 = 1
UNION
SELECT ID2 FROM YOURTABLE WHERE ID1 = 1
select id2 as FriendID from table
where id1 = 1
union
select id1 as FriendID from table
where id2 = 1
Use more descriptive names for starters
SELECT * FROM table WHERE id1=1 or id2=1 and id1<>id2
Related
Suppose I have a table with two columns:
TABLE A
-------
ProjectID NUMBER
STATUS VARCHAR2(6) // either 'CLOSED' or 'NEW'
There could be maximum two entries for a ProjectID with the two possible values of STATUS and the combination (ProjectID, STATUS) is unique.
I need to select only those ProjectID's that have status 'NEW'. Also, if for a projectID, there are two entries with different statuses (NEW and CLOSED), I don't want it in the output.
I tried using group by, then ordering the resultset descending (so as to get 'NEW' row for a project ID first) and then taking the first row in LINQ, similar to this:
var query = (from a in context.A.Where(o => o.STATUS == 'NEW')
group a by a.ProjectID into groups
select groups.OrderByDescending(o => o.ProjectID)
.ThenBy(o => o.STATUS)
.FirstOrDefault());
Butt it's resulting into an "APPLY" clouse in the query which is resulting into an error. Apparantly, Oracle 10g doesn't support it.
Any help is appreciated.
Something like this, perhaps?
SQL> with test (projectid, status) as
2 (select 1, 'new' from dual union -- should be returned
3 select 2, 'new' from dual union
4 select 2, 'closed' from dual union
5 select 3, 'closed' from dual union
6 select 4, 'new' from dual -- should be returned
7 )
8 select projectid
9 from test
10 group by projectid
11 having min(status) = max(status)
12 and min(status) = 'new';
PROJECTID
----------
1
4
SQL>
Proper tu use having count(distinct STATUS=1) :
create table tableA( ProjectID int, STATUS varchar2(10) );
insert all
into tableA values(1 ,'NEW')
into tableA values(1 ,'CHANGED')
into tableA values(2 ,'NEW')
into tableA values(3 ,'CHANGED')
select * from dual;
/
select * from
(
select ProjectID, max(STATUS) STATUS
from tableA
group by ProjectID
having count(distinct STATUS)=1
)
where STATUS = 'NEW';
I believe I have accomplished what you want, using a subquery in LINQ.
var query = (from a in context.A
where (from b in context.A
where b.ProjectID == a.ProjectID
select new { a.ProjectID, a.STATUS }).Distinct().Count() == 0
&& a.STATUS == "NEW"
select a.ProjectID).ToList();
Essentially, the outer query just makes sure that each a record has a NEW status, and the inner query makes sure that there are no two distinct records with the given ProjectID, because if there are, one is CLOSED. I avoided using a GROUP BY since you said your database does not support LINQ's way of doing it.
I hope I understood your problem correctly, and I hope this helps!
Hello this is what i have in mind but no idea how to properly do it.
Table1
ID ID2 Name Dosage
------------------------------
1 001 Name1 Dosage1
2 002 Name2 Dosage2
3 003 Name3 Dosage3
Table2
ID Quantity
------------------------
1 1000
2 2000
3 3000
Query something like:
Select ID,Name,Dosage from Table1 and Quantity(of the same ID from Table1)from Table2
where ID2 from Table1 ='002';
Datagridview Output
ID Name Dosage Quantity
---------------------------------
2 Name2 Dosage2 2000
A simple SQL join should work.
Try this :
select Table1.ID, Table1.Name, Table1.Dosage, Table2.Quantity
from Table1
inner join Table2 on Table2.ID = Table1.ID
where Table2.ID2 = '002';
From the comment you gave to the another answer. You should fix it to look like this:
DECLARE #SupID INT = 200049;
SELECT SP.ProductID, SP.Brand, SP.Dosage, P.Quantity
FROM Supplier_productlist AS SP
INNER JOIN Products AS P
ON P.ID = SP.ProductID
WHERE SP.SupplierID = #SupID;
In case SupplierID is a "string", declare it like this instead:
DECLARE #SupID NVARCHAR(10) = '200049';
Sorry I am really a newbie into programming and I am trying to merge two different columns into one column using sql but if it is not possible can it be done using sql code in c#?
I have two tables Product1 and Product2, these tables both have CatID.
For Product1, the CatID contains
1
2
3
For Product2, the CatID contains
1
2
3
4
5
The results that I am getting using union is if they have both similar id it will be merge into one and using concat it will duplicate into like
1 1
2 2
3 3
4
5
But the results that I want is the 1 to 3 is from product1 and then the 4 to 8 from product2 like it will continue on counting with no duplicate:
1
2
3
4
5
6
7
8
Is this possible?
Try it like this:
SELECT CatID, ...OtherColumns...
FROM Product1
UNION SELECT CatID, ...OtherColumns...
FROM Product2
WHERE Product2.CatID NOT IN(SELECT CatID FROM Product1)
ORDER BY CatID
(test here: http://sqlfiddle.com/#!9/7887c):
CREATE TABLE T1(ID INT, txt VARCHAR(10));
INSERT INTO T1 SELECT 1, 'test A'
UNION SELECT 2, 'test B'
UNION SELECT 3, 'test C';
CREATE TABLE T2(ID INT, txt VARCHAR(10));
INSERT INTO T2 SELECT 1, 'test 1'
UNION SELECT 2, 'test 2'
UNION SELECT 3, 'test 3'
UNION SELECT 4, 'test 4'
UNION SELECT 5, 'test 5';
SELECT ID, txt
FROM T1
UNION SELECT ID, txt
FROM T2
WHERE T2.ID NOT IN(SELECT ID FROM T1)
ORDER BY ID
The result:
ID txt
1 test A
2 test B
3 test C
4 test 4
5 test 5
I am not sure what you want but with LINQ you can create a select. If you show us the SQL code it would be very helpful.
can you try this query, use union
select * from Product1
union
select * from Product2 NOT IN(SELECT CatID FROM Product1)
I have following table structures.
**Table_A**
A_Id(BigInt) Category_Ids(varchar(50))
1 1,2,3
2 2,3
**Table_B**
B_Id(BigInt) C_Id(Bigint) Name(varchar(50))
1 2 A
2 1 C
3 3 B
First Query:
In this query want to get the record where A_Id=1. I have executed following code.
Select [Category_Ids] from Table_A where A_Id=1
This returns the data table with single column and single row with values “1, 2, 3”
Assume that above query fills the data into the A_datatable. I get the string from following code.
String ids = A_datatable.column[0][“Category_Ids”];
Second Query:
Now, I have to fetch the values from Table_B where C_Id in (1, 2, 3). I have executed following code and passed the string value to following query.
Select * from Table_B where C_Id in (ids)
When I execute above query getting the error, failed to convert parameter value from a String to a Int64.
You can actually do it in a single query.
SELECT b.*
FROM Table_A a
INNER JOIN Table_B b
ON ',' + a.Category_IDs + ',' LIKE '%,' + CAST(C_ID AS VARCHAR(10)) + ',%'
WHERE a.A_ID = 1
Caveat: This query is an index-killer. You should have properly normalize your tables.
UPDATE 1
Suggested Schema Design,
Table_A
A_ID
Category_ID
Table_C
B_ID
C_ID
Name
Records
Table_A
A_ID Category_ID
1 1
1 2
1 3
2 4
2 5
Table_B
B_Id C_Id Name
1 2 A
2 1 C
3 3 B
You can use a string splitter function like the one described here http://www.sqlservercentral.com/articles/Tally+Table/72993/
scroll down to the 'CREATE FUNCTION' script and run it to create your function, then you can split the comma separate string for use in your 'where in' clause
select * from Table_B
where C_Id in (select item from dbo.DelimitedSplit8K(IDS,','))
I am not sure even how to ask this question.
I have a table of tags:
TagId Tag
----- -----
1 Fruit
2 Meat
3 Grain
I have a table of events:
EventId Event
------- -----------
1 Eating Food
2 Buying Food
What I need to do is bring back only Events that have all selected tags associated with it.
If three tags are selected then only show event that have all three.
For example:
Mapping Table
EventId TagId
------- -----
1 1
1 3
2 1
If I write a query like this:
select * from MapTable where where tagId in (1,3)
This will return Eating Food and Buying Food.
But what I need to do is bring back events that have both tags 1 and 3. This means that the only event in this case I would return would be Eating Food as it has both selected tags.
I was wondering if this can be done in TSQL or if I will have to use the business layer to translate it into the object to return back to the GUI.
Thanks.
There was a very similar question yesterday: Query for exact match of users in a conversation in SQL Server
basically you can do this:
DECLARE #NumTags INT = 2
SELECT EventID
FROM EventTag
GROUP BY EventID
HAVING
Sum(CASE WHEN TagID IN (1, 3) THEN 1 ELSE 0 END) >= #NumTags
so this will find all events that both the tags exist in (this allows for instances where those two tags exist along with any additional tags)
Here is a solution for when you do not know the tags before hand.
Load the tags into a table variable and get the total count:
select #iCount = COUNT(*) from #Tags;
Then write your normal query and slam those results into a table variable:
insert into #EventTags(IsSet, EventId)
select distinct CASE WHEN TagID IN (select ID from #Tags) THEN 1 ELSE 0 END,
e.EventId
from Event_Tag e
inner join #Tags t on t.ID = e.TagId
Then to get back only Events that have ALL matching tags, not just ones that are in the selection, but ALL you do this:
select *
from Event_Tag e
inner join #Tags t on t.ID = e.TagId
where e.EventId in
( select EventId
from #EventTags
group by EventId
having count(EventId) = #iCount
)
Only bring back tags that have all tags associated.
Thank you again everyone for the ideas! Greatly appreciated all the feedback!
There's probably a better way to write it but this will give you what you are looking for:
select *
from event e
where exists(select * from maptable where eventid = e.eventid and tagid = 1) and exists(select * from maptable where eventid = e.eventid and tagid = 3)
You'll want to inner join the two tables, as follows
SELECT * FROM Events INNER JOIN MapTable ON MapTable.EventId=Events.EventID WHERE MapTable.TagID=1 AND MapTable.TagID=3