So i have a database with a number of AccountId's and GameId's. I want to get all entries where a where a specified AccountId is used, furthermore i only want them if the table contains a value pair where a specified accountID (different one) has the same GameId as for one of the entries gotten.
An example of this could be
AccountId
GameID
asd
123
zxc
123
zxc
789
In this example the AccountId zxc would be the first specified AccountId while asd would be the seccond.
In this case i only want the the following returned
AccountId
GameID
zxc
123
I hope this makes sense
SELECT t1.AccountId, t1.GameId
from TableName t1
inner join TableName t2 on
t1.GameId = t2.GameId
where t1.AccountId = 'Accountid1' AND t2.AccountId = 'AccountId2'
Related
I have two following tables.
Table A:
Email Phone
A#gmail.com 1234
B#gmail.com 2345
C#gmail.com 4567
D#gmail.com 5432
E#gmail.com 4568
Table B:
Email LinkName
A#gmail.com X
B#gmail.com Y
C#gmail.com
D#gmail.com X
B#gmail.com X
Desired Output:
Email LinkName
C#gmail.com
E#gmail.com
Following is the query which I tried. Please let me know is it correct:
Select Email from Table A
Left join Table B
on A.Email = B.Email
where C.LinkName is null
No, C.LinkName you don't have C table
SELECT
A.Email
FROM TABLE A
LEFT JOIN TABLE B
ON A.Email = B.Email
WHERE B.LinkName IS NULL
This one is the right one, LinkName is B column so you have to modify it in WHERE statement
If you want LinkName column (as in your desired output) you should add B.LinkName in your SELECT, but it will be filled with NULL values only
I'm stuck on writing this piece of code.
the output that i need to get is
firstName lastname Name Price Date
--------------- --------------- ------------------------- -------- ----------
Bateman Michael Furniture DR 222.80 2013-05-01
Tara Roswell Clothes Ladies 24.25 2013-05-04
LeMay Mike Toys Child 12.00 2013-05-12
Create a query that will show who picked up unsold items during the month of May 2013. Include in your output the first and last name of the owner, along with the name of the item, max price and pick up date. Order your output by Pick up date. My output looked like the following:
and my output is
FirstName LastName Name Price Date
--------------- --------------- ------------------------- ------- ----------
my code is
SELECT P.FirstName
, P.LastName
, IT.Name
, I.MaxPrice AS Price
, IP.Date
FROM People P
JOIN CHARITY C ON P.PeopleID = C.ContactID
JOIN Donation D ON C.CHARITYID = D.CHARITYID
JOIN Item_Donation ID ON D.DonationID = ID.DonationID
JOIN IteM I ON ID.ItemID = I.ItemID
JOIN Item_Type IT ON I.ItemTypeID = IT.ItemTypeID
JOIN Item_PickUp IP ON I.ItemID = IP.ItemID
ORDER BY IP.Date
I see nothing wrong with your query, so I suspect a data issue. Here is how I would investigate this. Start with querying the "root" table:
SELECT * FROM People p
If the results are not what you expect, then you have found the issue in your data.
If the results are ok, then add the first join:
SELECT *
FROM People P
JOIN CHARITY C ON P.PeopleID = C.ContactID
Same thing, if the results are not what you expect, then you have a data issue in the CHARITY table. Query the CHARITY table by itself to see why the rows from that table are not joining to People:
SELECT * FROM CHARITY
If the results are what you expect, then add the next JOIN, and continue, one JOIN at a time, until you find the one that causes no rows to be returned. Examine the data in that table to see why it doesn't join to your query before the join.
I have two tables one transaction and one master.
The master Table has more than one value for a primary key causing one to many relation and replicating the measures.
Is it possible to capture the actual value of measure at first occurrence and replace the other occurrence of same measure with 0?
This will help me keep the dimensional values but not aggregate the data repetitively.
Transaction table
Key Value
abc 240
def 120
Master Table
Key Dimension1 Dimension 2
abc subcode1 description of abc
abc subcode2 description of abc
def subcode1 description of abc
Output Required
Key Dimension1 Dimension 2 Value
abc subcode1 description of abc 240
abc subcode2 description of abc 0
def subcode1 description of abc 120
You will get the desired output from the below query
SELECT m.*
,(CASE WHEN ROW_NUMBER() OVER(PARTITION BY t.[Key] order by t.[Key]) = 1
THEN t.Value ELSE 0 END) AS Value
FROM Master_table as m
inner join Transaction_table as t on t.[Key] = m.[Key]
Here ROW_NUMBER() used to identify the first record in that [Key].
Lets say we have the following table structure:
DECLARE #Person TABLE
(
PersonId INT,
Name VARCHAR(50)
)
DECLARE #Address TABLE
(
AddressId INT IDENTITY(1,1),
PersonId INT
)
And we insert two person records:
INSERT INTO #Person (PersonId, Name) VALUES (1, 'John Doe')
INSERT INTO #Person (PersonId, Name) VALUES (2, 'Jane Doe')
But we only insert a address record for John
INSERT INTO #Address (PersonId) VALUES (1)
If I execute the following queries I get different results
SELECT *
FROM #Person p
LEFT JOIN #Address a
ON p.PersonId = a.PersonId AND a.PersonId IS NULL
PersonId | Name | AddressId | PersonId
1 | John Doe | NULL | NULL
2 | Jane Doe | NULL | NULL
VS
SELECT *
FROM #Person p
LEFT JOIN #Address a
ON p.PersonId = a.PersonId
WHERE a.PersonId IS NULL
PersonId | Name | AddressId | PersonId
2 | Jane Doe | NULL | NULL
Why are the queries returning different results?
The first query is not meeting any of your conditions. Hence it is displaying all results from the #Person table (Typical Left join). Where as in the second query, the where clause is applied after the join. Hence it is displaying proper result.
First:
get all records (two) from Person and join 0 records from Address, cos none of address have PersonID = NULL. After that no additional filters applyed. And you see two records from Person
Second:
get all records (two) from Person and one of them joined to Address with ID = 1. After that your WHERE filter applyed and one of records with joined ID = 1 disappears.
ON clause defines which all matching rows to show from both tables.
WHERE clause actually filters the rows.
In the 1st query, it is returning 2 rows because LEFT JOIN returns all the rows from the left table irrespective of match from right table.
2nd query is returning 1 row, because for PersonId=1, #Address table contains a matching record hence a.PersonId is NOT NULL.
Make it a habit to read your SQL query from the Where condition and then look at your joins, this will give you a clearer meaning/understanding of what is happening or going to be returned.
In this case you said WHERE a.PersonId IS NULL the Select Part must happen and It must Join using the following join criteria.
That is how your query is being read by your machine hence the different sets of results.
And then in contrast, on the condition where there is no where clause, the results on the Left table (p) do not have to exist on (a) but at the same time the results on (a) must be null but already they might not exist. Already at this point your SQL will be confused.
I have following Table
Table User
UserID Name
1 Om
2 John
3 Kisan
4 Lisa
5 Karel
Table Game
Games Players
Golf 1,3,5
Football 4
I wrote query:
Select UserId,
Name from User
Where UserID IN
(Select Players from Game where Games='Golf')
Result:
~~~~~~~
0 Rows
Above query does not return me any result while it works well when i directly specify values for In clause in statement.
Select UserId, Name
from User
Where UserID IN (1,3,5)
Result:
~~~~~~~
UserID Name
1 Om
3 Kisan
5 Karel
3 rows
However when I change the condition in very 1st query with Football:
Select UserId, Name
from User
Where UserID IN
(Select Players
from Game
where Games='Football').
This returns me following result:
UserID Name
4 Lisa
1 row
How I can work around so that my very 1st query returns me the right result?
I think I'm in wrong direction. Help me out!
This is what you get for storing comma separated values in a field. Now you have to split it, using, say this function and do something like
Select User.UserId, User.Name from User
inner join splitstring((Select Players from Game where Games='Golf')) a
on User.UserID = a.Name
But consider changing your table "Game" design to
Games Players
Golf 1
Golf 3
Golf 5
Football 4
Then you can do simple
Select User.UserId, User.Name
from User inner join Game
on User.UserID = Game.Players
Where Game.Games = 'Golf'
without any additional functions.
Your first query translates to this:
Select UserId, Name
from User
Where UserID IN (`1,3,5`)
Notice that it is a string representation of the IDs, not a comma separated list like in your second query.
There are many Split functions out there written for this very scenario.
You can utilize one of them as such:
DECLARE #PlayersCsv NVARCHAR(MAX)
Select #PlayersCsv = Players from Game where Games='Golf'
Select UserId,
Name from User
Where UserID IN
(Select Value FROM dbo.Split(#PlayersCsv, ','))
DECLARE #xml AS xml
SET #xml = (SELECT cast('<X>'+(''+replace(players,',' ,'</X><X>')+'</X>') AS xml)
FROM Game WHERE Games='Golf')
SELECT UserId, Name
FROM User
WHERE UserID IN
(SELECT N.value('.', 'varchar(10)') as value FROM #xml.nodes('X') as T(N))
SQL Fiddle Results:
| USERID | NAME |
|--------|-------|
| 1 | Om |
| 3 | Kisan |
| 5 | Karel |