sqlite join statement - database

I'm just learning join statements in sqlite and I'm having trouble with the the below example.
Here is the statement that has gotten me closest to the results I want:
select listings.id, listings.name, media.image from listing join media where media.listing_id = listings.id
listings:
id | name | phone
1 , john , 555-5555
2 , jane , 555-0000
media:
listing_id | image_url
2 , www.xyz.xyz
in return I want
id | name | image_url
1 , john
2 , jane , www.xyz.xyz

That should be
SELECT listings.id, listings.name, media.image_url
FROM listing LEFT JOIN media ON media.listing_id = listings.id
A "left join" gives you results from the left table (listing) even if there is no match in the right table (media). A regular join requires both to exist to give a result for that row.

Related

Select records when 2 column's data will match

I have two tables as shown below:
-----------------------
|EmpNo|Complaint |
-----------------------
|9091 |Change required|
|9092 |No change |
|9093 |Changes done |
-----------------------
Above table contains employee number and his complaints.
I have one another table which contains employee all kind of details as shown below.
-------------------------------
|EmpNo|EmailID |EmpBossNO|
-------------------------------
|9091 |abc#gmail.com|9092 |
|9092 |xyz#gmail.com|9093 |
|9093 |mno#gmail.com|9099 |
-------------------------------
Here, if Empno:9091 will raise any complain then a mail will send to his boss that the complain is raise by your employee and you have to accept it so I want to get EmailID of employee's boss and for that I want one SQL query. I tried the query shown here, but it doesn't work.
select EmpEmailID
from tblComplaint
inner join tblEmpMaster on tblEmpMaster.EmpNo = tblComplaint.EmpPSNo
where tblComplaint.EmpPSNo = tblEmpMaster.EmpBossNo
I want output like.. if complaint is raised by EmpNo:9091 then it will return EmailID of his boss which is xyz#gmail.com.
You are on the right track with a join between the tblComplaint and tblEmpMaster tables. But, you need an additional join to tblEmpMaster to bring in the boss' email for each employee complaint.
SELECT
c.EmpNo,
c.Complaint,
COALESCE(e2.EmailID, 'NA') AS boss_email
FROM tblComplaint c
INNER JOIN tblEmpMaster e1
ON c.EmpNo = e1.empNo
LEFT JOIN tblEmpMaster e2
ON e1.EmpBossNO = e2.EmpNo;
Demo
I used a left self join above, in case a given employee does not have a boss (e.g. for the highest ranking boss). In this case, I display NA for the boss email.
You should self join tblEmpMaster
select boss.EmpEmailID
from tblComplaint
inner join tblEmpMaster emp on emp.EmpNo = tblComplaint.EmpPSNo
inner join tblEmpMaster boss on boss.EmpNo = emp.EmpBossNO
where tblComplaint.EmpPSNo = 9091
DB Fiddle
you can even use sub queries to get the Email_Id of the boss as shown below
SELECT Email_Id
FROM EMP_Details
WHERE Emp_No IN (
SELECT Boss_Id
FROM Emp_Details) AND
Emp_No IN (
SELECT Emp_No
FROM Emp_Complaints)

Remove duplicate rows from query based on value in one column

I have a table (SQL Server) where I store the run status of all of our automated test cases and I'm trying to come up with an SQL query to retrieve the status per runid, but I'm running into some problems with it.
Example of data within the table:
KRUNID | KTIME | FK_TC_ID | NOPART | STATUS | ENV
-------+----------------+------------+--------+--------+-----
4180-2 | 20190109080000 | TC0001 | 123456 | Passed | INT
4180-2 | 20190109080100 | TC0002 | 123457 | Failed | INT
4180-2 | 20190109080200 | TC0003 | 123458 | Passed | INT
4180-2 | 20190109080400 | TC0002 | 123459 | Passed | INT
Right now, I have this query (the join statements are used to display the actual test case name and business domain):
SELECT KRUNID, TD_NAME, TS_NAME, FK_TC_ID, TC_DISPLAYNAME, NOPARTENAIRE,
ENV, STATUS FROM RU_RUNSTATUS
INNER JOIN TC_TESTCASES ON K_TC_ID = FK_TC_ID
INNER JOIN TS_TCSUBDOMAINS ON K_TS_ID = FK_TS_ID
INNER JOIN TD_TCDOMAINS on K_TD_ID = FK_TD_ID
WHERE KRUNID = '418-2'
ORDER BY FK_TS_ID, K_TC_ID
The query is basic and it works fine except that I will have 2 lines for TC0002 when I only want to have the last one based on KTIME (for various reasons I don't want to filter based on STATUS).
I haven't found the right way to modify my query to get the result I want. How can I do that?
Thanks
I think this article can be respond : Get top 1 row of each group
Look of your query with limit partioned by FK_TC_ID and ordered by KTIME
;WITH cte AS
(
SELECT FK_TS_ID, KRUNID, TD_NAME, TS_NAME, FK_TC_ID , TC_DISPLAYNAME, NOPARTENAIRE,
ENV, STATUS, ROW_NUMBER() OVER (PARTITION BY FK_TC_ID ORDER BY KTIME DESC) AS rn
FROM RU_RUNSTATUS
INNER JOIN TC_TESTCASES ON K_TC_ID = FK_TC_ID
INNER JOIN TS_TCSUBDOMAINS ON K_TS_ID = FK_TS_ID
INNER JOIN TD_TCDOMAINS on K_TD_ID = FK_TD_ID
WHERE KRUNID = '418-2'
)
SELECT *
FROM cte
WHERE rn = 1
ORDER BY FK_TS_ID, K_TC_ID

SQL query to get data from two rows connected by key

I have a question that seems very simple to me at first but I'm relatively new to SQL and I can't solve it.
I have two tables: 'Applicants' and 'Family Units'.
Applicants:
ApplicantID | FirstName
----------- | ----------
1 | John
2 | Mary
Family Units:
ApplicantID | UnitID| Note
1 | 10 | Member
2 | 10 | Mother
I need to bring in one table Applicant Name and Mother Name.
Mother applicantID should be determined by having same UnitID in Family Units table and Mother Note in the same table (and other details they are not relevant here).
I tried this query:
That obviously doesn't work correct, I get applicant name instead of applicant's mother's name.
Need you help, links to articles and explanations also will be great because I feel that I'm missing something very basic.
; with cte as
(
select fu.*,a.name from
FamilyUnit fu
join applicant a on a.id = fu.id
where type = 'Mother'
)
select a.id,a.name,c.name
from applicant a
join FamilyUnit fu on fu.id = a.id
join cte c on c.unit = fu.unit
where c.id <> a.id
Im not so sure if this is correct: just try it
select * from
(select * from #family_units where note = 'member') as a
left join
(select * from #family_units where note = 'mother') as b
on a.unitid = b.unitid
left join #applicant_table as c
on a.ApplicantID =c.ApplicantID
Test result:
1 10 Member 2 10 Mother 1 John

referencing three columns to same column in another table in sql server 2000

I have a question on SQL Server 2000, i need to get an report from database. I have database called Automation where it contains set of tables to handle the queries of ticketing process of our application.
I need to extract a report from database that should contain ticket number and user information like who has entered, received, edited , reviewed that ticket.
I need these fields from the database
Ticketnumber
billnumber
companyname
enteredby(username)
entereddate
recievedby(username)
recieveddate
editedby(Employeename)
editeddate
reviewedby(ReviewerName)
revieweddate
postedby(Managername)
posteddate
I have three tables
1> VPP_VendorBilldetails
BillentryID | ticketnumber | billnumber | VENDORNAME,BILLNUMBER,COSTCENTERNAME,BILLAMOUNT,TICKETDATE,BILLDATE | companyID(not companyname) | billdate | Enteredby(userid)| entereddate | recievedby(userid) | recieveddate | editedby(userid) | editeddate | reviewedby(userid) | revieweddate | postedby(userid) | posteddate
2> Users
UserID | employeeID | employeename |loginID| Password | usertype | status
3> VPP_ClientCompanyDetails :
companyid | companyname | companyaddress | status
I have written this query, but I am getting same employee name for all three categories :
SELECT CLIENTCOMPANYNAME, TICKETNUMBER,VENDORNAME,BILLNUMBER,COSTCENTERNAME,BILLAMOUNT,TICKETDATE,BILLDATE,
RECIEVEDDATE,EMPLOYEENAME AS EXECUTIVENAME,
VPP_VENDORBILLDETAILS.MODIFIEDDATE,
EMPLOYEENAME AS REVIEWERNAME,EMPLOYEENAME AS POSTEDBY,POSTEDDATE,ERRORCODE,
IMPACTCODE,ROOTCAUSE,REVIEWERREMARKS
FROM
VPP_VENDORBILLDETAILS
INNER JOIN
VPP_CLIENTCOMPANYDETAILS
ON VPP_VENDORBILLDETAILS.BILLENTEREDCOMPANYID = VPP_CLIENTCOMPANYDETAILS.CLIENTCOMPANYID
INNER JOIN USERS
ON VPP_VENDORBILLDETAILS.MODIFIEDBY = USERS.USERID
WHERE CONVERT(VARCHAR(12),CONVERT(DATETIME,POSTEDDATE,103),101)
BETWEEN CONVERT(DATETIME,CONVERT(VARCHAR(12),getdate()-7,100),101)
AND CONVERT(DATETIME,CONVERT(VARCHAR(12),getdate()-1,100),101)
AND VPP_CLIENTCOMPANYDETAILS.STATUS = 1 AND VPP_VENDORBILLDETAILS.STATUS = 1 AND USERS.STATUS = 1 AND ERRORCODE IS NOT NULL AND TALLYID IS NOT NULL
ORDER BY CLIENTCOMPANYNAME ASC
Please check it and help me on this
Please help me to extract the report the above said tables..
Try this :
SELECT CLIENTCOMPANYNAME, TICKETNUMBER,VENDORNAME,BILLNUMBER,COSTCENTERNAME,BILLAMOUNT,TICKETDATE,BILLDATE,
RECIEVEDDATE,U1.EMPLOYEENAME AS EXECUTIVENAME,
VPP_VENDORBILLDETAILS.MODIFIEDDATE,
U2.EMPLOYEENAME AS REVIEWERNAME,U3.EMPLOYEENAME AS POSTEDBY,POSTEDDATE,ERRORCODE,
IMPACTCODE,ROOTCAUSE,REVIEWERREMARKS
FROM
VPP_VENDORBILLDETAILS
INNER JOIN
VPP_CLIENTCOMPANYDETAILS
ON VPP_VENDORBILLDETAILS.BILLENTEREDCOMPANYID = VPP_CLIENTCOMPANYDETAILS.CLIENTCOMPANYID
INNER JOIN USERS U1
ON VPP_VENDORBILLDETAILS.recievedby = U1.USERID
INNER JOIN USERS U2
ON VPP_VENDORBILLDETAILS.MODIFIEDBY = U2.USERID
INNER JOIN USERS U3
ON VPP_VENDORBILLDETAILS.postedby = U3.USERID
WHERE CONVERT(VARCHAR(12),CONVERT(DATETIME,POSTEDDATE,103),101)
BETWEEN CONVERT(DATETIME,CONVERT(VARCHAR(12),getdate()-7,100),101)
AND CONVERT(DATETIME,CONVERT(VARCHAR(12),getdate()-1,100),101)
AND VPP_CLIENTCOMPANYDETAILS.STATUS = 1 AND VPP_VENDORBILLDETAILS.STATUS = 1 AND USERS.STATUS = 1 AND ERRORCODE IS NOT NULL AND TALLYID IS NOT NULL
ORDER BY CLIENTCOMPANYNAME ASC

How to effectively join 3 tables M:N

I have few tables:
Apps:
id | name | url_key
===================
1 | Hello World | hello-world
2 | Snake 2 | snake-2
Developers:
id | name | url_key
===================
1 | Mr. Robinson | mr-robinson
2 | Richard | richard
3 | Nokia | nokia
Apps-Developers-Assignment
app_id | developer_id
=====================
1 | 1
1 | 2
2 | 3
So as you may see, one app may have more than one developer.
What i actually need is to write a PostgreSQL query to select all apps with some usefull information about related developers.
e.g. sth like this:
Hello World | 1-hello-world | Mr.Robinson<1-mr-robinson> /and 1 more/
Snake 2 | 2-snake-2 | Nokia<3-nokia>
So if the app has one developer, just append the developer's name, url key and id to the app, if it has more developers, append the first and append the information of "how many developers are there".
And what's most important - i need to eventually filter the results (e.g. not return apps from some specified developer).
I know it can be solved by write first query for apps itself and then send next query per each row, but not the nice way, i think...
If i just simply JOIN the table:
SELECT * FROM apps a
LEFT JOIN apps_developers_assignment ada ON a.id = ada.app_id
LEFT JOIN developers d ON ada.developer_id = d.id
Hello World | 1-hello-world | Mr.Robinson<1-mr-robinson>
Hello World | 1-hello-world | Richard<2-richard>
Snake 2 | 2-snake-2 | Nokia<3-nokia>
It returns duplicate apps... and i don't know how to filter these results by developer (as i wrote above).
Assuming you only want to filter out one developer, you will need to pass a parameter. I am calling this parameter/variable #excludeDevId for this purpose.
I am much more familiar to T-SQL, so this may/will also need the equivalent syntax in Postgres. Also, I am leaving nulls as a result of the left join as null--from your output you probably want to COALESCE (probably some other output tweaks as well). This is off the cuff and untested, but should be enough to get you moving in the right direction at least:
SELECT
a.name AppName,
a.id AppId,
d.id DevId,
d.url_key Url,
d.name DevName,
CAST(agg.dev_count - 1 as VARCHAR) + ' more'
FROM
(
SELECT
MAX(ada.developer_id) first_dev_id,
COUNT(ada.developer_id) dev_count,
app_id
FROM
apps_developers_assignment ada
WHERE
d.id != #excludeDevId
GROUP BY
app_id
) agg
INNER JOIN apps a ON a.id = agg.app_id
LEFT JOIN developers d ON agg.developer_id = d.id
If you want to use a left join, you'll need to put your condition on the join, otherwise it'll crate an inner join and the rows that have null in won't get returned... try something like this:
SELECT * FROM apps a
LEFT JOIN apps_developers_assignment ada ON a.id = ada.app_id
AND ada.developerid = :devid
LEFT JOIN developers d ON ada.developer_id = d.id
WHERE a.id = :appid

Resources