I have two tables, one with data for one type of ID (call it key1) and a table where this ID (call it key2) is transformed to another. It is not one-to-one match with these types of ID and I want to check those key2 cases that have two or more key1 linked to it.
It is simple enough and for the easiest check I don't even need table1 to run it as table2 has both key1 and key2 variables.
However, not all doubles are of identical worth. Table1 (that has only key1) has a year variable. I am interested in doubles that have same year variable, ie. in table1 there are two key1 cases with the same year variable that are linked to one key2 case in table2.
So in essence in table1 I have key1, year and in table2 I have key1, key2 and I am interested in those key2-cases that have more than one key1 linked to it where years are the same.
SELECT query.key2
FROM (
SELECT DISTINCT a.key1, b.key2
FROM table1 AS a JOIN table2 AS b ON a.key1=b.key1 JOIN table1 AS c ON
a.key1=c.key1
WHERE a.year=c.year)
AS query
GROUP BY query.key2
HAVING COUNT(*)>1
I tried it joining table1 twice and fiddling around with various JOIN and WHERE clauses (the one on show being the simplest and most naive one) but the query still returns key2-doubles whose key1 cases are linked to different years. It is simple enough if you give a distinct year value in where clause (and drop second table1 join as unnecessary) but I don't want to go through all years manually one by one. I was thinking some kind of iterative loop that changes the value of the year in where clause could do the trick (and be heavy computationally) but I don't really know how to go around doing it, haven't done any loops in SQL ever.
Hi, This is a really complicated issue and is hard to explain but i have the following:
select name, MAX(table2.time) from table1 INNER JOIN table2 on table1.id = table2.id GROUP BY name
which is fine and brings up the correct results but if I want to find out from those records what another field is in table 2 for each record it pulls up too many results (i want just the one result from table 2 and then find what user it is)
if I do..
select name, table2.username MAX(table2.time) from table1 INNER JOIN table2 on table1.id = table2.id GROUP BY name, table2.username
.. it pulls up too many results cos there are different usernames
if i dont group by table2.username then it give an error
Just curious. The exec plan is the same for both qry's, and they both show the same estimated row counts @ the point of question in the exec plan. The exec times are roughly the same, any variances I'm attributing to db load from other things going on, since any benefits of one over the other are not consistent from execution to execution. So is there any benefit to filtering in the join conditions vs. the where clause? My thinking was that by filtering earlier in the qry (when joining) as opposed to "waiting" to do it in the where clause, the rest of the qry after the join would inherently be dealing w/a smaller result set for the rest of it's execution, thus improving performance. After the exec plan checking I did, I guess I was wrong. Seems that Sql Server is intelligent about such filtering when analyzing the entire qry, and building its execution accordingly. The execution plan for both qry's showed the same where clause argument for the tables being joined.
Filtering in where clause....
Code:
select... FromtProject p with (noLock) jointProjectCall pc with (noLock) on P.ID = pc.project_id jointStore S with (noLock) on pc.store_id = s.id jointZip Z with (noLock) on Z.zip5 = s.zip5 jointManager M on M.ID = case ... end leftjoin ( selectprojectCall_RecNum as RecNum, sum(answer) as HoursUsed fromtCall C whereAnswer > 0 and question_id in (1, 2) group by projectCall_Recnum ) as C on pc.recnum = c.recnum wherepc.removed = 0 andp.cancelled = 0 andp.deleted = 0 ands.closed = 0 ands.deleted = 0 andyear(getDate()) between year(P.startDate) and year(P.expDate)
Filtering in joins...
Code:
select... FromtProject p with (noLock) jointProjectCall pc with (noLock) on P.ID = pc.project_id and pc.removed = 0 and p.cancelled = 0 and p.deleted = 0 and year(getDate()) between year(P.startDate) and year(P.expDate) jointStore S with (noLock) on pc.store_id = s.id jointZip Z with (noLock) on Z.zip5 = s.zip5 and s.closed = 0 and s.deleted = 0 jointManager M on M.ID = case ... end leftjoin ( selectprojectCall_RecNum as RecNum, sum(answer) as HoursUsed fromtCall C whereAnswer > 0 and question_id in (1, 2) group by projectCall_Recnum ) as C on pc.recnum = c.recnum
Hi. I am working on a procedure which can filter data through three tables. First Table is User --------------------------- UserName UserID ---------------------------
Second Table is Customer --------------------------- UserID Cust_Site_Int_ID ---------------------------
Third Table is l Details --------------------------------------------------------------- Cust_Site_Int_ID Created_Date Status ----------------------------------------------------------------
I want to create a stored procedure which can filter through these tables. I will have four input fields in my application to accept parameters. The four parameters will be UserName, two date fields which specifies a range of dates and status. I want the filter to work like this, if only one parameter is provided it will use only that parameter if additional parameter is given it will use the AND logic.
I tried to do a Proc but it is not working any way here it is. So you will get a better idea of what I am trying to achieve.
set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go
-- ============================================= ALTER PROCEDURE [dbo].[FilterServiceTickets] -- Add the parameters for the stored procedure here @userName varchar(20)= NULL, @startDate datetime =NULL , @endDate datetime = NULL, @status int = NULL AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;
-- Insert statements for procedure here SELECT SERVICE_TICKET.SERVICE_TICKET_CODE, SERVICE_TICKET.PROBLEM_REPORTED, SERVICE_TICKET.CONTACT_NUMBER, SERVICE_TICKET.STATUS FROM aspnet_Users INNER JOIN BuildingAddress ON aspnet_Users.UserId = BuildingAddress.UserID INNER JOIN SERVICE_TICKET ON BuildingAddress.Customer_Site_Int_ID = SERVICE_TICKET.CUST_SITE_INT_ID WHERE ((aspnet_Users.UserName = @userName)OR (@userName=NULL)) AND ((SERVICE_TICKET.STATUS = @status) OR (status=NULL)) AND ((SERVICE_TICKET.CREATED_DATE >=@startDate AND SERVICE_TICKET.CREATED_DATE <=@endDate ) OR (@startDate=NULL)OR (@endDate=NULL)OR(@startDate=NULL AND @endDate=NULL)) END
I have a complex join filtering on a replicated sql server database which was working fine in previous versions of sql compact. The query is something like the following:
SELECT <published columns> FROM <filtered table> INNER JOIN <child table> ON <child table>.ID = <filtered table>.ID and <child table>.date > getdate()-30 After I upgraded to compact databse 3.5, for some weird reason whichever tables have both these Join filter and article filter together behaving improperly. If I insert any row in any of these table, the row is replicated properly to the server, but it does not send the new row to any other users. Again this thing works fine in older version. I have switched back tyo the old version of sql ce and again it's started working.
Why does this right join return the same results as using a left (or even a full join)?There are 470 records in Account, and there are 1611 records in Contact. But any join returns 793 records.
select Contact.firstname, Contact.lastname, Account.[Account Name] from Contact right join Account on Contact.[Account Name] = Account.[Account Name] where Contact.[Account Name] = Account.[Account Name]
I am trying to generate a report that is basically a class list. It lists classes for a specific semester and lists them by day of the week and then by time.
If I am pulling back a dataset of all classes, how do I filter my report so as to show each set of classes appropriately (by day and by time within the day)? I tried using the Filter function on the table level, but I guess I don't get it.
i have a query with some inner joins that return information about an employee
i am running into a problem in that i need one employees email based on one inner join and anothers based on another inner join -- is there a way to get both in one query?
select employee.email , bunch of other stuff from work
INNER JOIN technician ON business_location.technician_id = technician.technician_id
inner join salesrep on business_location.salesrepid = salesrep.salesrep_id
not sure how to get both of those to employee.emp_id and get the email
Hello, first post since I can usually find answers by reading the forums. I've searched the internet up and down and for some reason I can't get this query to work properly.
I have two tables:
ticket
ticket_id ticket_to ticket_from
message
message_id ticket_id message
There can be several messages per ticket, connected by the ticket_id. I'd like to only pull only the most recent message, as well as the results from the ticket table. Currently I'm getting all messages per ticket.
Here's what I have:
SELECT distinct ticket.ticket_to, ticket.ticket_from, message.ticket_id, message.message FROM tickets INNER JOIN message ON tickets.ticket_id = message.ticket_id GROUP BY message.ticket_id, message, ticket_to, ticket_from
Any help would be greatly appreciated! Thanks much.
Table 3 holds the persons or groups to whom we have given a copy of a specific part.
PersonsCopiedAt pca_id integer primarey key pca_wpd_id integer foreing key from WordPartDoc pca_pg_id integer this is the id of the table that holds the persons or the id of the table that holds the group pca_p_or_g char(1) this is a flag : 'P' for a person, 'G' for a group
Now, here is my problem... I have created the following sql query select wd_id, wpd_id from wordDoc inner join wordPartDoc on wpd_wd_id = wd_id inner join PersonCopiedAt on pca_wpd_id = wpd_id where pca_pg_id = someID and pca_p_or_g = 'G' --or 'P'
This works perfectly if a pca_pg_id is provided, but this is provided using a combobox... If the user doesn't select a person - and thus - no id is provided - inner join brings me as many records of wpd_id as the number of persons that were given a copy. I understand that this is the correct behaviour but in the later case (when no id is provided) i want only one record to be returned. Is there a way to do so ? do i have to redisign the db schema ?
I have been using T-SQL for a while now although the majority of my work required relativley simple queries. I just need to know is there a way to JOIN the results of several SELECT queries, maybe through the use of functions??
A reference to any online article would be most helpful.
Trying to cross-update 2 tables. Picture a checkbook reconcilliation without common check numbers. The checkbook has uniqueids and the bank has transaction ids but they are different. So the match is on date/payee and amount. So I wrote 2 checks to the same person, on the same day, for the same amount but forgot to enter one in the register.
when i run the update statement: update b set b.bankid=c.myid from checks c join bank b on c.cdate=b.cdate and c.payee=b.payee and c.cost=b.cost
Both bank statement records would be updated to my one check record [can't happen] Also: this will be running on a hundred thousand records per month with potential for duplication/ommission on either side.
What's a poor newbie missing?? I'm doing something similar on a lesser volume by running sequential statements through an ASP script but performance is poor. I know SQL can do this, just not how to approach it.
Hi, I have three tables: 1 Order Details 2 Product Info 3 Received Qty
The query is pretty simple however I'm getting incorrect results.
The query grabs a load of information (including a SUM statement) from the order details tbl.. this is INNER JOIN ed to the products tbl to match an ID field which grabs some extra info from the product info tbl.
all fairly straightforward and works without a problem..
However I now need to add in the received qty tbl (as the name suggests this keep a track of the qty's of items received)
I need to join this tbl to the order details tbl based on a unique ID from the orders tbl and then SUM together all of the entries in that received qty tbl for that item.
Result is I get a single record which shows the qty ordered (from the order details tbl), and the total received (from the received qty) tbl
These are held in a seperate tbl as an order can be deliveryed in several stages.
Here is my statement:
SELECT PDS_Login.Supplier_Products.ProductName, PDS_Login.Supplier_Products.ProductCode, dbo.Suppliers_POs_Details.POID, dbo.Suppliers_POs_Details.PODetailsID, dbo.Suppliers_POs_Details.Qty, dbo.Suppliers_POs_Details.PricePerItem, dbo.Suppliers_POs_Details.PoDetailsStatus, dbo.Suppliers_POs_Details.PoDateExpected, dbo.Suppliers_POs_Details.PODateReceived, SUM(dbo.Suppliers_POs_Details.Qty * dbo.Suppliers_POs_Details.PricePerItem) AS LineTotal, SUM(dbo.Suppliers_POs_Details_Received.Qty) AS QtyReceived FROM dbo.Suppliers_POs_Details INNER JOIN PDS_Login.Supplier_Products ON dbo.Suppliers_POs_Details.ProductID = PDS_Login.Supplier_Products.ProductID LEFT OUTER JOIN dbo.Suppliers_POs_Details_Received ON dbo.Suppliers_POs_Details.PODetailsID = dbo.Suppliers_POs_Details_Received.PODetailsID WHERE (dbo.Suppliers_POs_Details.POID = @POID) GROUP BY dbo.Suppliers_POs_Details_Received.Qty, PDS_Login.Supplier_Products.ProductName, PDS_Login.Supplier_Products.ProductCode, dbo.Suppliers_POs_Details.POID, dbo.Suppliers_POs_Details.PODetailsID, dbo.Suppliers_POs_Details.Qty, dbo.Suppliers_POs_Details.PricePerItem, dbo.Suppliers_POs_Details.PoDetailsStatus, dbo.Suppliers_POs_Details.PoDateExpected, dbo.Suppliers_POs_Details.PODateReceived, dbo.Suppliers_POs_Details_Received.Qty
The problem is, if there is more than one relating record in teh Received Qty tbl instead of that being added together as I want, two results appear...
It's obviously something simple but I can't seem to figure it out - anyone point me in the right direction?
ON dbo.Track_ID.SM_ID = dbo.transactions.sm_session_id
GROUP BY dbo.Track_ID.TrackID
)
) Once moved to SQL Server 2005 the statement would not return and showed SOS_SCHEDULER_YIELD to be the waittype when executed. This machine is SP1 and needs to be upgraded to SP2, something that is not going to happen near time.
I changed the SQL to the following, SQL Server now runs it in under a second, but now the app is not functioning correctly. Are the above and the following semantically the same?
UPDATE dbo.Track_ID
SET dbo.Track_ID.Processed = 4 --Regular 1 leg call thats been completed
I want to select all usernames from tlbUsers which practice a certain sport.I also have a table UsersAndSports:UserID intSportID intI therefore need an inner join statement:select username from(SELECT ROW_NUMBER() OVER (ORDER BY au.LastActivityDate DESC) as RowNum,ud.username from tblusers usinner join tblUsersAndSports uas on uas.usercode=us.usercode and (uas.sportID=3 or uas.sportID=4)WHERE us.UserName <>'' )as MemberInfo WHERE RowNum between (@startRowIndex+1) AND (@startRowIndex+@maximumRows)The problem lies in the usage of the ROW_NUMBER command. I need that in order to effectively page through my records, but it also makes thatI cant make a distinct selection as each RowNum is unique....:SIn case the user would practice 2 sports, the query would return 2 rows...if I place a distinct in front of the username as such:select distinct username fromThe query would return each user only once...BUTBUTBUT: my startrowindex and maximumrows apply to the results that can be found in the MemberInfo selection..so lets say my startrowindex would be 0 and maximumrow 5if my 1st query (without distinct) was to return:johnjohnjohnjohnmikemikerobmy 2nd query (with distinct) would return:johnmikewhereas I want it to return:johnmikerobWhat can I do?
I have a SELECT Statement that I am using that is pulling from two tables. There won't always be results in the second table so I made a LEFT OUTER JOIN. The problem I am having is that I need to have three conditions in there:WHERE (employee.emp_id = @emp_id) AND (request.requested_time_taken = 'FALSE') AND (request.request_end_date >= GETDATE()))The two conditions from the request table are causing the entire query to return NULL as the value. I need help trying get a value whether or not there are any results in the request table.Here is the full select statement:SELECT (SELECT SUM(ISNULL(request.request_duration, '0')) AS Expr1 FROM employee LEFT OUTER JOIN request AS request ON employee.emp_id = request.emp_id WHERE (employee.emp_id = @emp_id) AND (request.requested_time_taken = 'FALSE') AND (request.request_end_date >= GETDATE())) AS dayspending FROM employee AS employee_1 LEFT OUTER JOIN request AS request_1 ON employee_1.emp_id = request_1.emp_id WHERE (employee_1.emp_id = @emp_id) GROUP BY employee_1.emp_id, employee_1.emp_begin_accrual, employee_1.emp_accrual_rate, employee_1.emp_fname, employee_1.emp_minitial, employee_1.emp_lname
SELECT EventID, Role, EventDuty, Qty, StartTime, EndTime, Hours FROM dbo.tblEventStaffRequired;
and SELECT EventID, Role, StartTime, EndTime, Hours, COUNT(ID) AS Booked FROM tblStaffBookings GROUP BY EventID, Role, StartTime, EndTime, Hours;
How can I join the results of the two by matching the columns EventID, Role, StartTime and EndTime in the two and have the following columns in output EventID, Role, EventDuty, Qty, StartTime, EndTime, Hours and Booked?
Hi, I have a query written in SQL 2000 which returns incorrect result. The query uses left outer join and a view. I read an issue related to this in one of microsoft bug report in this article http://support.microsoft.com/kb/321541.
However, there's a slight difference in the sympton second bullet wherein instead of a expression the query returns a fixed string for one of the column value.
Although the issue mentioned in article seems to be fixed. The later one still seems to be reproducible even with Service Pack 4. However, this issue doesn't appear in SQL Server 2005.
Here's the query to reproduce this error.
Code Snippetcreate table t1 (pk1 int not null,primary key (pk1)) create table t2 (pk1 int not null,label1 varchar(10) not null,primary key (pk1)) go insert into t1 values (1) insert into t2 values (2, 'XXXXX') go create view V as select pk1, 'ZZZZ' as label1 from t2 go select A.pk1 as A_pk1, B.pk1 as B_pk1, B.label1 as B_label1 from t1 as A left outer join V as B on A.pk1 = B.pk1 go
This query is similar to the one mentioned in the article except that in the SELECT clause of CREATE VIEW statement I am passing a fixed value for column "label1".
I just want to confirm that this is an issue and no fix is available for this so far.
What I would like to end up with is a pivot table of each account, the trigger code and service codes attached to that account, and the rate for each.
I have been able to dynamically get the pivot, but I'm not joining correctly, as its returning every dynamic column, not just the columns of a trigger code. The code below will return the account and trigger code, but also every service code, regardless of which trigger code they belong to, and just show null values.
What I would like to get is just the service codes and the appropriate trigger code for each account.
SELECT @cols = STUFF((SELECT DISTINCT ',' + ServiceCode FROM TriggerTable FOR XML PATH(''), TYPE ).value('(./text())[1]', 'VARCHAR(MAX)') ,1,2,'')
Hi I have a strange issue here. Both the input datasets of the merge join are sorted . Everything works fine if the dataset doesn't contain speacial characters like - (hipen). This is the sorted dataset.ASI311_3ASI311_3ASI312ASI311ASIKit1ASIKit1
Merge Joiner has to look for ASI311 and finds it in the list and everything works as expected. But if the dataset is changed to
ASI311_3ASI311_3ASI-312ASI311ASIKit1ASIKit1
Then it doesn't find the ASI311 in the above dataset ? Only change between the two datasets is the - (hipen) which is added in one of the field. Does SSIS has a differenent precedence of the special characters than that of the Database. Both the datasets are on SQLServer.
Hello! I've got the following procedure: ALTER PROCEDURE [GetTimeDiff2] (@ID int) AS select A_ProspectPipeline.ID, (case when [Completion Date] is null then '13' else case when YEAR([Completion Date])>year(GETDATE()) then '13' else case when YEAR([Completion Date])<year(GETDATE()) then '1' else month([Completion Date]) end end end)- (case when YEAR([Start Date])=year(GETDATE()) then month([Start Date]) else case when YEAR([Start Date])<year(GETDATE()) then '1' else '13' end end)as [CY],
(case when [Completion Date] is null then '13' else case when YEAR([Completion Date])>year(GETDATE())+1 then '13' else case when YEAR([Completion Date])<year(GETDATE())+1 then '1' else month([Completion Date]) end end end)- (case when YEAR([Start Date])=year(GETDATE())+1 then month([Start Date]) else case when YEAR([Start Date])<year(GETDATE())+1 then '1' else '13' end end)as [NY]
from a_ProspectPipeline where A_ProspectPipeline.ID = @ID
What i need to do is insert the two returned values [NY] + [CY] into two different tables. Can anyone help me with this?
I have a quick question for the SQL community about how to combine 3 tables to get the results needed...
The table names are : setup_zipcode, setup_category, and listing
and inside setup_zipcode it has the columns: zip_id , zip_code, zip_latitude and zip_longitude
and inside the setup_category it has the columns: category_id, category_parent, category_path and category_name
and the final table for listing has the columns: listing_id, listing_member, listing_category, listing_address, listing_city, listing_state, listing_zip and listing_country
I am having trouble getting them to inter-relate an query the needed results as I need to get back the LAT & LONG from the zip_latitude & zip_longitude columns for specific listing ids in certain categories...
So, the ONLY same variable between them is that listing_zip from LISTING table and zip_code from SETUP_ZIPCODE show the same zip codes..
How can I create a SQL query that checks the current category that is being displayed on the page results live and insert only the listing id (clients) that are in that listing_category and also pull that listing_id client's related zip_latitude & zip_longitude that relates to their specific listing_zip from the zip_code row in setup_zipcode?
I have tried many things and this looks like it would work but does not pull the related LAT & LONGs ...
$cat is assigned in a query previously on the page...
SELECT * FROM setup_zipcode, setup_category, listing WHERE listing_category LIKE '%-$cat-%' AND listing_zip = zip_code AND category_id = '$cat' ORDER BY listing_title ASC
When I try to take the results (not sure if I am missing a step for printing the results after querying them or having to assign them somehow) and use the SMARTY TAGS assigned to zip_latitude and zip_longitude nothing shows on the published page... The other variables for the address do..
I have a loop defined as $listing_id and section is var so when I pull the query info using {$listing_address[var]}, {$listing_city[var]}, etc.. they work, but {$zip_latitude[var]} or {$listing_id[var].$zip_latitude} and {$listing_id[var].zip_latitude} so on do not work..
If I can get the variables to exist in the SQL QUERY then at least I will know that is correct and can work on how to get them to show correctly in the address for a map afterwards...
This seems like a very simple question but i have never been able tofind an easy answer to it.I have a user table and i do a join with another table, we'll call theother table a results table.The results table has numerous rows with the userid foreign key.I want to make a query that will give me the number of rows in theresults table for each user where the result is some valueThe query is simple to make but will only show the users who have arecord in the results table the meet the where criteria, however i wantto display each user and show a record count of 0 when there are noresults in the results table that match the criteria.for example i have 2 tables.tblUsers_______________userid | username--------------------------1 | user12 | user2tblAnswers________________userid | answer----------------------------1 | 11 | 01 | 42 | 12 | 0if i run the query:select max(username), count(answer) from tblUsersleft outer join tblanswers on tblAnswers.userid = tblUSers.idwhere tblAnswers.answer = 4group by tblUsers.idi just getuser1 | 1i want to getuser1 | 1user2 | 0the only way ive found to do this is with a temp table and a curser tocreate all the users records and go back through an insert the answercount for each user. This approach seems very expensive and requires aquery that is 3 times larger than is needed for the same resultswithout including 0 count records. I know there must be a better way todo this.Any help is appreciated.
I need to select Server1, Server2, Server3 and other servers that does not have correct value in Table2. Results should return server name and number that server does not have like:
Server2 | 3 Server3 | 1 Server3 | 3
Table1 is updated time to time, Table2 - static table. The best would be to avoid loop or cursor. Is that possible to get these results in one query?
I have created a new reports application project in VS 2008. I have a dataset with 2 tables: Customer and CustomerAddress with one to many relationship. I want to have a simple table in my report which displays data in the following format: Customer Name Address ---------------------------------------------------------- ABC Add1 ABC Add2
XYZ Add1 XYZ Add2
Here Address is obviously from CustomerAddress table. I have tried few options but it's mainly disgusting to work with Reports Application project when there was an amazing Busines Intelligence Reports project available in VS 2005 and equally good designer interface (Dataset, Design and Preview tabs for each report). Please give me a solution to this.
below is my statement to get data from one column (VARCHAR) from table SUPPLY_ITEM_01
SELECT @@SERVERNAME as ServerName,DB_NAME() AS DatabaseName, SUM(CASE WHEN CHARINDEX (CHAR(013) , supplydetail) > 0 THEN 1 ELSE 0 END) AS TotalCHAR013, SUM(CASE WHEN CHARINDEX (CHAR(012), supplydetail ) >0 THEN 1 ELSE 0 END)AS TotalCHAR012, SUM(CASE WHEN CHARINDEX (CHAR(010), supplydetail ) >0 THEN 1 ELSE 0 END) AS TotalCHAR010, SUM(CASE WHEN CHARINDEX (CHAR(009),supplydetail ) >0 THEN 1 ELSE 0 END) AS TotalCHAR009 FROM
[code]...
I need to get result from all the tables and all the columns which has bad data including schemaName, table name and column name in result.