I was tasked to look up several tickets in the database that hit certain criteria. But I think I am at the limitations of what SQL can handle. The below has an issue because all tickets that belong to company '1646' are like over 12k tickets for that customer alone...
So at first I thought about an inner join statement, but then I started to get a headache as things kept looping around itself. Below is the script that attempts to run, but then my database starts to smoke... And suffers read/write issues. The lag becomes very real and it is very clear to see it is from me pulling this query. The culprit:
SELECT
s.SR_Service_RecID as 'Ticket #',
t.Description as 'Description',
s.Summary as 'Summary Description',
d.Date_Created as 'Entered',
b.Board_Name as 'Board',
c.Company_ID as 'Company',
q.Description as 'Status',
p.SR_Severity_Name as 'Priority',
a.Description as 'Type',
z.Description as 'SubType',
s.Date_Closed as 'Closed'
d.SR_Detail_Notes_Markdown as 'Notes',
From
dbo.SR_Service as s,
dbo.SR_Type as t,
dbo.SR_Detail as d,
dbo.SR_Board as b,
dbo.Company as c,
dbo.SR_Status as q,
dbo.SR_Severity as p,
dbo.SR_Type as a,
dbo.SR_Subtype as z
WHERE
s.Company_RecID like '1646'
and s.Entered_By not like 'zadmin'
and s.Updated_By not like 'zadmin'
and s.Entered_By not like 'RESTAPI'
and s.Updated_By not like 'RESTAPI'
and s.Entered_By not like 'techautomate'
and s.Updated_By not like 'techautomate'
and s.Entered_By not like 'template%'
and s.Updated_By not like 'template%'
and s.Entered_By not like 'HelpDesk'
and s.Updated_By not like 'HelpDesk'
and s.Entered_By not like 'Email Connector'
and s.Updated_By not like 'Email Connector'
and d.SR_Detail_Notes_Markdown not like '%Assigned%'
ORDER BY
s.Date_Entered ASC;`
How can I refine this into a better query or change 8 of inner joins to make this work? How can I make am SQL script for?
First he Friendly names and then the primary key and foreign key relations:
ticket number = Service_RecID is the primary key in dbo.Service foriegn key in dbo.Detail
ticket type = SR_Type_RecID is the primary key in the dbo.Type foreign key in dbo.Service. But I need the description of that id which is in dbo.type.
Summary Description = is located in dbo.SR_Service the column header is Summary
Entered (is the date the ticket was entered) = located in dbo.SR_Detail under the column header Date_created.
Board (is the service board ticket is assigned to) = SR_Board_RecID primary key in dbo.SR_Board foreign key in SR_Service. But I need the column header Board_Name located in dbo.SR_Board.
Company = Company_RecID primary key in dbo.Config, but the foreign key in dbo.SR_Service
Status = SR_Status_RecID primary key dbo.SR_Status foreign key is located in dbo.SR_Service
Priority = SR_Severity_RecID primary key for dbo.SR_Severity foreign key is located in dbo.SR_Service. But I need SR_Severity_Name which is the column header in dbo.SR_Severity
type = SR_Type_RecID primary key in dbo.Type shares foreign key with dbo.Service. But I need the description associated with SR_Type_RecID located in dbo.SR_Type
subtype = SR_SubType_RecID primary key located in dbo.SR_subtype and the foreign key that is shared is under dbo.SR_service. But again I need the description that is under the dbo.SR_SubType.
closed = as it is located in the dbo.SR_Service under column header date_closed
notes = on the other hand is located in dbo.Detail under column header SR_Detail_Notes_Markdown and the only keys it shares across the database is a foreign key SR_Service_Rec_ID
I can’t seem to get the INNER JOIN statements to work properly.
INNER JOIN dbo.SR_Service.Service_RecID on dbo.SR_Detail.Service_RecID
INNER JOIN dbo.Type.SR_Type_RecID on dbo.SR_Service.SR_Type_RecID
INNER JOIN dbo.Type.Description on dbo.SR_Service.Type_Description
INNER JOIN dbo.SR_Board.SR_Board_RecID on dbo.Service.SR_BoardRecID
INNER JOIN dbo.Config.Company_RecID on dbo.Service.Company_RecID
INNER JOIN dbo.SR_Status.SR_Status_RecID on dbo.Service.SR_Status_RecID
INNER JOIN dbo.SR_SubType.SR_Type_RecID on dbo.Type.SR_Type_RecID
I think it is how I am declaring my FROM Statement...
Can I not just run singular database queries and have the results dump and append to a new database object?
The JOIN condition is how one table is related to another based on a common column. Aside from your specific query, think of orders.
An order is made by a customer. An order has details, order detail products are from a products table.
Having said that, you might want something like
select
c.customername,
o.orderdate,
od.qty,
p.productname
from
customer c
join orders o
on c.customerid = o.customerid
join orderDetails od
on o.orderid = od.orderid
join products p
on od.productid = p.productid
FEEDBACK FROM EDITS you provided in your original question
Now that you have provided respective primary key and foreign keys, we can help a little further. First, dont try to name your columns with spaces or special characters like 'Ticket #'. It is typically easier to name them readable in 'CamelCaseWhereUpperPerWord' is just an example. The output via whatever method should worry about the formatting of such header columns in output.
Next, when applying filters, such as your company number, if its a number, dont put it in quotes, leave it as a number for equality testing. In this case, you are looking for tickets for a single
company = 1646. I would ensure an index on the service table including that column as an index in its first position.
From your edited PK/FK, I have revised the query as below with embedded comments
SELECT
-- per ticket found
s.SR_Service_RecID TicketNumber,
-- dont worry about renaming Summary AS SummaryDescription,
-- let the OUTPUT process add whatever column headers is more common approach
-- just get the column and get it to work first, then fine-tune it
s.Summary,
s.Date_Closed Closed,
-- dont worry for now about specific column order, I am trying to match
-- the hierarchy of data trying to acquire. You want for a specific company,
-- so I am just putting that up front for now.
c.Company_ID Company,
-- description from the TYPE table
t.Description type,
-- pull from sub-type of the type
st.Description SubType,
-- now I can pull columns from the SR_Detail table
d.Date_Created Entered,
d.SR_Detail_Notes_Markdown Notes,
-- now any columns from the SR_Board table
b.Board_Name Board,
-- columns from the status table
q.Description Status,
p.SR_Severity_Name Priority
From
-- or is this table SUPPOSED to be Service vs SR_Service
SR_Service as s
-- first, joining to the config table so you can get the descriptive company "name", such as your "Company_ID"
JOIN Config as c
on s.Company_RecID = c.Company_RecID
-- now join the outer hierarchy SR_Service to the SR_Type on its PK/FK relationship
join SR_Type as t
on s.SR_Type_RecID = t.SR_Type_RecID
-- changing the subtype to a LEFT-JOIN in case a sub-type does not exist
LEFT JOIN SR_Subtype as st
on s.SR_SubType_RecID = st.SR_SubType_RecID
-- now join the outer hierarchy SR_Service to the SR_Detail on its PK/FK relationship
-- or is this table SUPPOSED to be Detail vs SR_Detail
JOIN SR_Detail as d
on s.Service_RecID = d.Service_RecID
-- doing a LEFT-JOIN since an entry may NOT be assigned to a board (yet).
-- otherwise the ticket will be excluded from final list if no such board assignment
LEFT JOIN SR_Board as b
on s.SR_Board_RecID = b.SR_Board_RecID
-- etc., similar joins to each other lookup table for clear descriptions based on given PK/FK relationship
JOIN SR_Status as q
on s.SR_Status_RecID = q.SR_Status_RecID
JOIN SR_Severity as p
on s.SR_Severity_RecID = p.SR_Severity_RecID
WHERE
-- NOW, you can apply your filtering conditions here as you have them
s.Company_RecID = 1646
and s.Entered_By not like 'zadmin'
and s.Updated_By not like 'zadmin'
and s.Entered_By not like 'RESTAPI'
and s.Updated_By not like 'RESTAPI'
and s.Entered_By not like 'techautomate'
and s.Updated_By not like 'techautomate'
and s.Entered_By not like 'template%'
and s.Updated_By not like 'template%'
and s.Entered_By not like 'HelpDesk'
and s.Updated_By not like 'HelpDesk'
and s.Entered_By not like 'Email Connector'
and s.Updated_By not like 'Email Connector'
and d.SR_Detail_Notes_Markdown not like '%Assigned%'
ORDER BY
s.Date_Entered ASC;
Now that you have a full query, in the future, take one piece at a time. Look at what you wanted. All tickets associated with one customer. Query just that. As you have a table (or alias), get all the columns you expect from that one before moving on. Ex:
select
s.SR_Service_RecID TicketNumber,
s.Summary,
s.Date_Closed Closed
from
SR_Service s
where
s.Company_RecID = 1646
Great, this gets you the immediate result of the tickets. But now you want more stuff. So, one table at a time, do a join. How does the second table relate to the first. I always try to list my primary (in this case your service table) on the left (or first position) JOINING a second table (right-side) based on what FK/PK relationship. In this case, you want the in-the-clear company name from the Config table. So, get that extra column based on the join itself.
select
s.SR_Service_RecID TicketNumber,
s.Summary,
s.Date_Closed Closed,
-- and now columns from next table
c.Company_ID Company
from
SR_Service s
JOIN Config as c
on s.Company_RecID = c.Company_RecID
where
s.Company_RecID = 1646
Continue adding one table at a time and one WHERE clause at a time until the entire query is done. In SQL-Server, by doing a
SELECT TOP 10 (rest of query)
will result the list to only 10 records. This way, you can sample "Does this query work as written?" Do you get an answer? Have you botched the command already? Fix it early one piece at a time. Column between each column retrieved. Do I have the proper JOIN condition between the two tables? then move on.
Hopefully this detailed example of your database scenario will help you learn to write queries easier. Also see how to better list your table structures (ALL RELEVANT COLUMNS) to help get better responses vs us trying to guess at column names in tables.
As Martin Smith says, you need to define the table joins. As the query stands now, any results would be useless.
To do this, you must first understand the database schema. More specifically, the relationship between the entities (= tables). For this you need to know and understand the business domain and how it is represented in the tables.
The SQL Server experts from this site will not be able to do this for you without the knowledge of the business domain.
After you have achieved the above you can deduce the correct joins from the database schema and improve your query draft accordingly.
I have two tables. delayedFlights which has these following attributes:
ID_of_Delayed_Flight
Month
DayofMonth
DayOfWeek
DepTime
ScheduledDepTime
ArrTime
ScheduledArrTime
UniqueCarrier
FlightNum
ActualFlightTime
scheduledFlightTime
AirTime
ArrDelay
DepDelay
Orig
Dest
Distance
and airport which has these attributes:
airportCode
airportName
City
State
I am trying to write a query which Lists the top 5 distinct states in which a flight between different airports within the same state has been delayed (either in arrival or departure) by descending order with respect to number of such delays. I'm not really sure how to write this query as I'm not sure how to query both tables at the same time, could someone give me any pointers on how to do this?
This is what I've tried
SELECT state, COUNT(*) AS num_delays
FROM delayed_flights
WHERE state = state
GROUP BY state
ORDER BY num_delays DESC
LIMIT 5;
(But obviously does not work)
You just need to understand joins you have to join to airport twice once for origin once for destination. we add aliases to make it easier to read and know the source tables of the selected fields. we can group by just origin or destination state since we're checking to make sure they are the same. Inner join requires an entry in both tables for a record to show. left/right (outer joins) show all records from one table and only those that match from the other whereas full outer shows all records from both tables even if no match is found. and cross join shows all records linked to all records in both tables.
This does assume that org and dest are related to the airportcode in the delayed flights table.
SELECT o.state, COUNT(*) AS num_delays
FROM delayed_flights df
INNER JOIN airport O
on o.airportCode = df.orig
INNER JOIN airport D
on d.airportCode = df.dest
WHERE O.state = D.state
GROUP BY o.state
ORDER BY num_delays DESC
LIMIT 5;
I just started using SQL and I need some help. I have 4 tables in a database. All four are connected with each other. I need to find the amount of unique transactions but can't seem to find it.
Transactions
transaction_id pk
name
Partyinvolved
transaction.id pk
partyinvolved.id
type (buyer, seller)
PartyCompany
partyinvolved.id
Partycompany.id
Companies
PartyCompany.id pk
sector
pk = primary key
The transaction is unique if the conditions are met.
I only need a certain sector out of Companies, this is condition1. Condition2 is a condition inside table Partyinvolved but we first need to execute condition1. I know the conditions but do not know where to put them.
SELECT *
FROM group
INNER JOIN groupB ON groupB.group_id = group.id
INNER JOIN companies ON companies.id = groupB.company_id
WHERE condition1 AND condition2 ;
I want to output the amount of unique transactions with the name.
It is a bit unclear what you are asking as your table definitions look like your hinting at column meanings more than names such as partycompany.id you are probably meaning the column that stores the relationship to PartyCompany column Id......
Anyway, If I follow that logic and I look at your questions about wanting to know where to limit the recordsets during the join. You could do it in Where clause because you are using an Inner Join and it wont mess you your results, but the same would not be true if you were to use an outer join. Plus for optimization it is typically best to add the limiter to the ON condition of the join.
I am also a bit lost as to what exactly you want e.g. a count of transactions or the actual transactions associated with a particular sector for instance. Anyway, either should be able to be derived from a basic query structure like:
SELECT
t.*
FROM
Companies co
INNER JOIN PartyCompancy pco
ON co.PartyCompanyId = pco.PartyCompanyId
INNER JOIN PartyInvolved pinv
ON pco.PartyInvolvedId = pinv.PartyInvolvedId
AND pinv.[type] = 'buyer'
INNER JOIN Transactions t
ON ping.TransactionId = t.TransactionId
WHERE
co.sector = 'some sector'
I have 3 data tables.
In the entries data table I have entries with ID (entryId as primary key).
I have another table called EntryUsersRatings in there are multiple entries that have entryId field and a rating value (from 1 to 5).
(ratings are stored multiple times for one entryId).
Columns: ratingId (primary key), entryId, rating (integer value).
In the third data table I have translations of entries in the first table (with entryId, languageId and title - translation).
What I would like to do is select all entries from first data table with their titles (by language ID).
On a top of that I want average rating of each entry (which can be stored multiple times) that is stored in EntryUsersRatings.
I have tried this:
SELECT entries.entryId, EntryTranslations.title, AVG(EntryUsersRatings.rating) AS AverageRating
FROM entries
LEFT OUTER JOIN
EntryTranslations ON entries.entryId = EntryTranslations.entryId AND EntryTranslations.languageId = 1
LEFT OUTER JOIN
EntryUsersRatings ON entries.entryId = EntryUsersRatings.entryId
WHERE entries.isDraft=0
GROUP BY title, entries.entryId
isDraft is just something that means that entries are not stored with all information needed (just incomplete data - irrelevant for our case here).
Any help would be greatly appreciated.
EDIT: my solution gives me null values for rating.
Edit1: this query is working perfectly OK, I was looking into wrong database.
We also came to another solution, which gives us the same result (I hope someone will find this useful):
SELECT entries.entryId, COALESCE(x.EntryUsersRatings, 0) as averageRating
FROM entries
LEFT JOIN(
SELECT rr.entryId, AVG(rating) AS entryRating
FROM EntryUsersRatings rr
GROUP BY rr.entryId) x ON x.entryId = entries.entryId
#CyberHawk: as you are using left outer join with entries, your result will give all records from left table and matching record with your join condition from right table. but for unmatching records it will give you a null value .
check out following link for the deta:
http://msdn.microsoft.com/en-us/library/ms187518(v=sql.105).aspx
I have following query, but it doesn't return any results for where clauses, even when there is row with that kind of name what is queried. If I remove where clause, then all records in Company table which have OfficeLocation table are returned. What is wrong in my query?
SELECT c.*
FROM [MyDb].[dbo].[Company] AS c
INNER JOIN [MyDb].[dbo].[CompanyOfficeLocation] AS col ON c.Id = col.CompanyId
INNER JOIN [MyDb].[dbo].[OfficeLocation] AS ol ON ol.Id = col.OfficeLocationId
WHERE ol.Name like '%Actual Name In This Table%';
Table structure :
Company
Id
etc ...
CompanyOfficeLocation
CompanyId
OfficeLocationId
OfficeLocation
Id
etc ...
Two things for a record to show up given your query:
The OfficeLocation you specified (given the ol.Name value) must have an Id value that is used by a record in the CompanyOfficeLocation table in its OfficeLocationId.
The CompanyOfficeLocation record that you got in #1 must have a CompanyId that exists in the Company table.
If any of those two criteria are not met, then no records will show up in your query result. The INNER JOIN is essentially an 'AND' clause. If a record could not be related to at least one INNER JOINed table, then that record will not show up at all.
If you want a record to show up despite not having any related records in the joined tables, you may want to consider using OUTER JOINs. A RIGHT JOIN in your case to be exact.
I do not find any mistake however I'd suggest you switch the columns after ON when joining to maintain standards.
Instead of - INNER JOIN [MyDb].[dbo].[OfficeLocation] AS ol ON ol.Id = col.OfficeLocationId
Do - INNER JOIN [MyDb].[dbo].[OfficeLocation] AS ol ON col.OfficeLocationId = ol.Id