I need to run a SELECT DISTINCT query acrossmultiple fields, but I need to add another field that is NON-DISTINCTto my record set.Here is my query:SELECT DISTINCT lastname, firstname, middleinitial, address1,address2, city, state, zip, age, genderFROM gpresultsWHERE age>='18' and serviceline not in ('4TH','4E','4W')and financialclass not in ('Z','X') and age not in('1','2','3','4','5','6','7','8','9','0')and (CAST (ADMITDATE AS DATETIME) >= DATEDIFF(day, 60, GETDATE()))ORDER BY zipThis query runs perfect. No problems whatsoever. However, I need toalso include another field called "admitdate" that should be treatedas NON-DISTINCT. How do I add this in to the query?I've tried this but doesn't work:SELECT admitdateFROM (SELECT DISTINCT lastname, firstname, middleinitial, address1,address2, city, state, zip, age, gender from gpresults)WHERE age>='18' and serviceline not in ('4TH','4E','4W')and financialclass not in ('Z','X') and age not in('1','2','3','4','5','6','7','8','9','0')and (CAST (ADMITDATE AS DATETIME) >= DATEDIFF(day, 60, GETDATE()))ORDER BY zipThis has to be simple but I do not know the syntax to accomplishthis.Thanks
I want to know how to create a recursive loop/function in SQL, I can’t seem to figure out how to do it. The database table I am working with is simply the following: SeedID, ThisParentSeedID 1, 0 2, 1 3, 1 4, 2 5, 4 6, 5 7, 6 8, 7 9, 7 10, 7 11, 10 12, 0 13, 0 14, 0 The example table above shows that SeedID 1 = the parent level of the data. SeedID 2 and 3 are children of SeedID 1, 4 is child of 2, 5 is child of 4... 12 13 and 14 are also parent levels (they are not children of anything). I want to know how to create a SQL script that is “object oriented� in that I will not have to create as many levels of nested scripts as there are nested “children� in the data. What I am wanting to figure out is, with a single script, “which sub-children are assigned to [@SeedID]�? So if this script was called, and @SeedID = 1, it would return (2,3,4,5,6,7,8,9,10,11). If @SeedID = 12, it would return null. If @SeedID = 7, it would return (8,9,10,11) I have tried to keep my question and data as simple as possible for the sake of getting some feedback or help. If you want me to clarify or explain better, please ask me to!
Hello Folks,I encountered a problem with SQL server 2000 and UDFs.I have a scalar UDF and a table UDF where I would like the scalar UDFto provide the argument for the table UDF like in:SELECT*FROMtransaction_tWHEREtrxn_gu_id in (select get_trxns_for_quarter(get_current_quarter( GetDate() ) ))'get_current_quarter' returns an integer which is a GUID in a tablecontaining business quarter definitions, like start date, end date.'get_current_quarter' is a scalar UDF.'get_trxns_for_quarter' will then get all transctions that fall intothat quarter and return their GUID's in a table.'get_trxns_for_quarter' is a table UDF.This doesn't seem to work at all. Regardless whether I provide thenamespace (schema) calling the scalar UDF or not. Error message isjust different.Both functions operate correctly invoked un-nested.The whole expression does work fine if I turn 'get_trxns_for_quarter'into a scalar UDF as well, e.g. by returning just one trxn_gu_id withe.g. MAX() in a scalar datatype. But of course that's no good to me.It also works fine if I select the result of 'get_current_quarter'into a variable and pass that variable into 'get_trxns_for_quarter'.But that's no good to me either since then I cannot use the wholething embedded into other SELECT clauses.Both UDF's are non-deterministic but I couldnt see how that would havean impact anyway.Never mind the syntax on that example or anyhting, I tried all theobvious and not so obvious stuff and it really seems to come down tothe fact that one UDF is scalar and the other one is not. However, Idid not come across any type of information saying that this cannot bedone.Have you any ideas?Any help would be greatly appreciated.Carsten
Im reading some guys code and I see the following code "select distinct(State) from listOFschools;select * from listOFschools" He is trying to query out states and the schools that are within the state. What exactly is the distinct() function do. and if anyone can tell me, what exactly is he asking to do in this statement
I have a query that returns employee names and reservations they updated for a set date. Here's a simplified version:
Select Employee.Name, Reservation.ResID From Employee INNER JOIN Reservation ON Employee.EmpID = Reservation.EmpID Where Reservation.DateModified BETWEEN '200510010000' AND '200510050000'
The problem is each employee can update the same reservation several times but I only want it to display that record once. The distinct statement doesn't work because I want the EmpID to be listed more than once. Thanks.
I have a query with DISTINCT option. If i use DISTINCT option with aggregate function like SUM will it eliminate duplicate values and then sum the values of a column and what is the syntax for it.
EX I have a column for budget
BUDGET 100 350 275 350 100
so if i use DISTINCT SUM(BUDGET) will it eliminate duplicate values and sum the total.
I need to return a single, unique record for each director. In my example here, I'm getting back 5 records for Bossidy because he has 5 records in the Directorships table each with a unique CompID.
SELECT TDirectors.IDDir, TDirectors.DirFName, TDirectors.DirLName, TDirectors.DirLName + ', ' + TDirectors.DirFName AS DirFullName, TDirectors.ExecutiveTitle, TDirectors.DirGender, TDirectors.DirAge, TDirRace.DirRace, TDirectors.PrincipalCompany AS CompanyName, TDirectorships.CompID FROM TDirRace RIGHT OUTER JOIN TDirectors ON TDirRace.IDDir = TDirectors.IDDir RIGHT OUTER JOIN TDirectorships ON TDirectors.IDDir = TDirectorships.IDDir WHERE (TDirectors.DirLName='Bossidy')
The result is accurate but the query execution time is 3-4 minutes for 10 fact records, when i use multiple dimension. it is showing me 0 valus for this measure for all the members for the dimesion attribute which doen't have any customer order. example it shows all the member of date dimension. is there any way to reduce the rows. i think this is the reason to take more execution time.when i use EXCCLUDEEMPTY the result is NULL
I have data in a table Item_TB that I need to extract in a way that pulls out the distinct pax name and all the ticket numbers associated with the passenger per booking reference.
The data is:
Branch Folder ID Pax TktNo BookingRef HQ 123 1 Jim 4444 ABCDE HQ 123 2 Bob 5555 ABCDE HQ 123 3 Jim 6666 ABCDE HQ 123 4 Bob 7777 ABCDE HQ 124 1 Jenny 8888 FGHIJ HQ 124 2 Jenny 9999 FGHIJ HQ 124 3 Jenny 3333 FGHIJ
I somehow need to get a function to pull the data out for each booking ref like so
--BookingRef ABCDE Jim 4444/ 6666 Bob 5555 7777 --BookingRef FGHIJ Jenny 8888/ 9999/ 3333
I know I can get a simple function to return the all data, but I do not know how to only include the pax name once.
do i need to nest a query in RS if i want a calculated column to be compared against a multi value variable? It looks like coding WHERE calcd name in (@variable) violates SQL syntax. My select looked like
SELECT ... ,CASE enddate WHEN null then 1 else 0 END calcd name FROM... WHERE ... and calcd name in (@variable)
Hi,Please can somone help me with a nested SQL query. I have two tables please see belowTable 1CallIDEmployeeIDCallSummaryCallStatusTable 2CallHistoryIDCallIDDataAddedCallActionI would like to return the CallID, EmployeeID, CallSummary and CallStatus from Table 1, and also display the last CallAction from Table 2.This is a helpdesk database so a Call will have many CallActions i.e. Open, Held, Assigned Internal. How do I return the last CallAction Added against the selected CallID, I know I use the DateAdded but not sure about nested statements.The results I would like to return to the user would look like this:-Call ID: 1EmployeeID: 1Call Sumary: SQL ProblemCall Status: OpenCall Action (Last Action): Assigned Internal.
I want to write one query which will select multiple distinct records from one table For e:g Lets say in a table i have 3 fields name,tel_no,sex Now i want to list all the records which are distinct in each of these fields like distinct name,distinct address
Important Tables: Product (table of products) --ProductID --ProductName
ProductCategories (Associates a Product with one or more categories) --ProductID --CategoryID
Category (table of categories that a product may fall under) --CategoryID --CategoryName
Information:
Basically I have a product that falls into two categories. Therefore there are two records in the ProcuctCategories Table. I am trying to create a query that will find all products that are in categories 1 & 2.
Attempted Solution: SELECT * FROM Product WHERE (ProductID IN (SELECT CategoryID FROM ProductCategories WHERE CategoryID =1)) AND (ProductID IN (SELECT CategoryID FROM ProductCategories WHERE CategoryID =2))
This returned zero records though it should have returned the product that is in categories 1&2.
HiI have 2 tables. The first has employee information and the second haspayroll information. I need to find out people who are not in thepayroll but in the employee table.Since the payroll has multiple instances i have to filter it and findout for each payroll.I don't think i have explained it very well so here is the data set.hope someone can help me with this.Thanks in advancepritTbl EmployeePlanIDSSN100111111111110012222222221001333333333TblPayrolldetailIDNumPlanID SSN11001111111111110012222222222100122222222221001333333333Required RESULT required(Missing employees from payroll)IDNumSSN13333333332111111111
Hello Everyone,I am trying to create a query for the purpose of a nested repeater relation. The information needs to be pulled from one table. I have shortened the columns to the ones that are required.table - PagesIDPageNameParentPageIDSo, take the following example:ID 14, PageName - Service A, ParentPage ID = 6ID 15, PageName - Service B, ParentPage ID = 6ID 36 PageName - Client 1, ParentPage ID = 14ID 37 PageName - Client 2, ParentPage ID = 14ID 38 PageName - Client 3, ParentPage ID = 15ID 39 PageName - Client 4, ParentPage ID = 15 So, I want to create a query that will get my nested repeater to display as follows:Service A Client 1 Client 2Service B Client 3 Client 4What I have come up with so far is:SELECT * from tbl_Pages WHERE ParentPageID IN (Select ID From tbl_Pages)SELECT p.ParentPageID, p.PageName, p.ID FROM tbl_Pages pThe relation would be based off ParentPageID. I keep getting errors that either there is no unique value or the relation is null. What am I am missing here?
Hi,I'm probably missing something obvious (either that or doing this totally wrong).I'm trying to use a nested loop to generate the following results:Unit Day1 Day2 Day3 Day4 Day5Name1 25 45 89 54 76Name2 48 54 81 74 98What I have so far is this:WHILE @FCount < @TotalFoodUnitsBEGINSELECT (SELECT Unit FROM tbl_acc_FoodVenues WHERE UnitID = (@FCount + 1)) AS Unit WHILE @FDCount < @Days BEGIN SELECT (SELECT FdRevenue_a FROM tbl_acc_aud_SportsAudits WHERE AudDate = DATEADD(day, @FDCount, @pdStartDate)) AS Rev SET @FDCount = @FDCount + 1 END SET @FCount = @FCount + 1ENDAny suggestions please
I am trying to write a query that does not use inner joins to see if it returns rows faster than a query using inner joins. My trouble is that I don't know how to write the syntax for the 3rd table that I am comparing against. Can I nest Exists in a Where clause? If so how is the 2nd exists statement added to the query? see my sample query below ================================================== === 'With 2 tables
SELECT DISTINCT s1.ID, s1.SITE FROM SITE_TBL s1 WHERE EXISTS (SELECT * FROM DEVICE_TBL d1 WHERE s1.ID = d1.SITE_ID AND d1.DELETEFLAG <> 'D') ORDER BY SITE
'with 3 tables this doesn't work
SELECT DISTINCT s1.ID, s1.SITE FROM SITE_TBL s1 WHERE EXISTS (SELECT * FROM DEVICE_TBL d1 WHERE s1.ID = d1.SITE_ID AND d1.DELETEFLAG <> 'D') AND (SELECT * FROM BIG_TBL b1 WHERE d1.fqdn = b1.xyz) ORDER BY SITE
================================================== === Thanks for the help Jim
Hi, I have the following scenario that I am not sure how to best tackle. Any advice or examples is appreciated.
I am creating a stored proc that requires a code to be passed to it. In return data gathered from 3 different tables will be returned. The big catch is that 1 of the tables resided in a differenct database.
So, here is the data layout.
Database 1, Table 1 contains the following fields: Job, CustID, ShipID, and ShipMethod.
So the first question is how should the stored proc look with an input parameter of "Job" and output of Job, CustID, ShipMethod, ShipID, Address, City, State, Zip, and CustomerName?
Secondly, which database should the stored proc reside?
Again, any advise, suggestions, pointers, etc. are appreciated.
Can anybody please tell me if a query such as this (Valid in MS Access) can work in SQL Server:
SELECT Description, Sum(Total) FROM ( SELECT Description, Total FROM Table_A UNION ALL SELECT Description, Total FROM Table_B UNION ALL SELECT Description, Total FROM Table_C ) GROUP BY Description
The group of unions work by themselves, but when I try to nest an outer query to do some a Summation(), I have syntax errors.
Any insight would be greatly appreciated. Thank you.
SELECT SUM (dbo.HOLDING.Shares_Par_Value_Qty * dbo.ASSET.Current_Prc) AS MarketValue FROM dbo.HOLDING INNER JOIN dbo.ASSET ON dbo.HOLDING.Property_Num = dbo.ASSET.Property_Num Group by dbo.HOLDING.Account_ID
Account_ID is the same in both the queries ie in both the tables Holding and Account.
I need the output like this
Select Account_Id, Branch_Cd, MarketValue from -------
But MarketValue should be calculated exactly in the above method. How do I combine these two queries. I need it asap. Help me out.
I have a database that contains a PERSONNEL table, a VISIT table, and a STARSHIP table. I am trying to generate a single column list of the personnel that are from Vulcan (PERSONNEL.PLANET) and all starships that have visited Vulcan (VISIT.PLANET). VISIT.SHIP and STARSHIP.REGISTRY columns contain the ships identifiers. How would I accomplish this? I am just beginning sql so please be nice ;)
I have the following result set #1 from the query below. As you can see, there are four different provider roles and four different physicians listed for the same case (acctnum). Is there a way I could add a nested select (or other method) which would allow me to list this case as one line item to appear in the manner of result set #2?
RESULT SET #1 (the results of the query I have now)
MRN ACCTNUM PTNAME AGE ADMDT DISCHDT LOS PROVIDER_CODE PROVIDER_ROLE PHYSNAME
12345 11111117777 DOE, JANE 48 Nov 29 2006 Nov 30 2006 1 10 ANE1 MILLER DR.
12345 11111117777 DOE, JANE 48 Nov 29 2006 Nov 30 2006 1 20 ADM MAY DR.
12345 11111117777 DOE, JANE 48 Nov 29 2006 Nov 30 2006 1 30 ATT SCHULTZ DR.
12345 11111117777 DOE, JANE 48 Nov 29 2006 Nov 30 2006 1 35 PRIN THOMAS DR.
RESULT SET #2 (this is how I desire the results to look)
MRN ACCTNUM PTNAME AGE ADMDT DISCHDT LOS ANE1PHYS ADMPHYS ATTPHYS PRINPHYS
12345 11111117777 DOE, JANE 48 Dec 13 2006 Dec 14 2006 1 MILLER DR. MAY DR. SCHULTZ DR. THOMAS DR.
Select
e.medrec_no,
e.account_number,
Isnull(ltrim(rtrim(pt.patient_lname)) + ', ' ,'')
+
Isnull(ltrim(rtrim(pt.patient_fname)) + ' ' ,'')
+
Isnull(ltrim(rtrim(pt.patient_mname)) + ' ','')
+
Isnull(ltrim(rtrim(pt.patient_sname)), '')
AS SRM_PatientName,
pm.PatientAge,
left(e.admission_date,11) as Admit_Date,
left(e.episode_date,11) as Disch_Date,
(CASE WHEN DATEDIFF(DAY, e.admission_date,e.episode_date) = 0 Then 1
ELSE DATEDIFF(DAY, e.admission_date,e.episode_date) END) AS LOS,
epi.PROVIDER_CODE,
epi.PROVIDER_ROLE,
pe.PERSON_NAME as physician_name,
From srm.episodes e inner join
dbo.PtMstr pm on pm.accountnumber=e.account_number inner join
srm.ITEM_HEADER ih ON ih.ITEM_KEY = e.EPISODE_KEY INNER JOIN
srm.PATIENTS pt ON pt.PATIENT_KEY = ih.LOGICAL_PARENT_KEY inner join
srm.CDMAB_PROV_EPI epi on epi.episode_key=e.episode_key inner join
srm.providers p on p.provider_key = epi.provider_key inner join
srm.person_element pe on pe.item_key = p.provider_key
Where e.episode_date is not null and pm.AnyProc like '%4495%'
How to configure sqldatadapter with query like "select name ,id from tlb1 where id in (select id from tlb2 where dept=@dept)" Is the nested subquery is not allowed while configuring sqldaadapter? Swati
I need to create a query to list all the subfolders within a folder.
I have a database table that lists the usual properties of each of the folder.
I have another database table that has two columns
1. Parent folder 2. Child folder
But this table maintains the parent child relationship only to one level.
For example if i have a folder X that has a subfolder Y and Z. And Y has subfolders A and B. and B has subfolder C and D and C has subfolder E and F
The database table will look like
parentfolder child folder X Y X Z Y A Y B B C B D C E C F
I want to write a query which will take a folder name as the input and will provide me a list of all the folders and subfolders under it. The query should be based on the table (parent - child) and there should not be any restriction on the subfolder levels to search and report for.
I have been banging my head to do this but i have failed so far. Any help on this will be highly appreciated.
I'd appreciate some help with the issue below - my SQL is a bit rusty and was never that hot to be frank. I'm using SQL Server 2000 (although have a test box with 2005 Express also). I've trawled MSDN and a few forums but can't find the solution (maybe I don't know what I'mm looking for!), so any help would be marvellous...
I have a table with a field called 'IRV' containing a string of comma-separated values. I want to be able to query a point in that string and count the number of times a given value appears. So...as an example, I want to count how many times '1' appears at position 7 in the IRV. I can create SQL to do this as follows:
SELECT COUNT(X) AS is1 FROM myIRVtable WHERE (SUBSTRING(IRV, 7, 1) = '1')
So far so good. However, it is also possible that the value at position 7 in this string could be '2' (or '3', or '4', etc) - and rather than re-running the query again and again to get these values, I'd like to do it in one hit.
How can I combine all this together - anyone have any brilliant solutions?
I have a table that refers to itself, and I need to loop through it to get the total number of entries in the structure with an object_type of 40 this is the function I came up with to do this. The problem is that the nested function doesn't seem to get called.
Code Snippet using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Collections.Generic; using Microsoft.SqlServer.Server;
public partial class StoredProcedures { private struct PerformanceCriteriaCounter { public PerformanceCriteriaCounter(int id, string objecttype) { Id = id; Object_Type = objecttype; } public int Id; public string Object_Type; }
[Microsoft.SqlServer.Server.SqlProcedure(Name = "usp_PerformanceCriteriaCounter")] public static int CountPerformanceCriteria(int ParentID, int SourcePosition) { using (SqlConnection conn = new SqlConnection("context connection=true")) { int Counter = 0; int Counter2 = 0; SqlContext.Pipe.Send("Called with ParentID=" + ParentID + " SourcePosition=" + SourcePosition); conn.Open(); using (SqlCommand myCommand = conn.CreateCommand()) { myCommand.CommandText = @"SELECT CompetenceLearningObject.Object_Type, CompetenceLearningObject.LearningObject_ID FROM CompetenceLearningObjectParent INNER JOIN CompetenceLearningObject ON CompetenceLearningObjectParent.LearningObject_ID = CompetenceLearningObject.LearningObject_ID WHERE (CompetenceLearningObjectParent.Approved = 1) AND (CompetenceLearningObject.Archived = 0 OR CompetenceLearningObject.Archived IS NULL) AND (CompetenceLearningObject.Approved_Status = 1) AND (CompetenceLearningObjectParent.Parent_ID = @ParentID) AND (CompetenceLearningObjectParent.Position_ID = @SourcePosition)"; myCommand.Parameters.AddWithValue("@ParentID", ParentID); myCommand.Parameters.AddWithValue("@SourcePosition", SourcePosition); List<PerformanceCriteriaCounter> loList = new List<PerformanceCriteriaCounter>(); SqlDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { SqlContext.Pipe.Send("Adding item"); loList.Add(new PerformanceCriteriaCounter(int.Parse(reader["LearningObject_ID"].ToString()), reader["Object_Type"].ToString())); } reader.Close();
I am trying to limit a result set by ROW_NUMBER. However, I am having problems getting it working.
The following query works fine, and I get a result set with PollID, AddedDate and RowNum columns.
SELECT *, ROW_NUMBER() OVER (ORDER BY Results.AddedDate DESC) AS RowNum FROM
( SELECT DISTINCT p.PollID, p.AddedDate
FROM vw_vs_PollsWithVoteCount p
JOIN vs_PollOptions o ON p.PollID = o.PollID
) AS Results
However, as soon as I add a WHERE condition:
SELECT *, ROW_NUMBER() OVER (ORDER BY Results.AddedDate DESC) AS RowNum FROM
( SELECT DISTINCT p.PollID, p.AddedDate
FROM vw_vs_PollsWithVoteCount p
JOIN vs_PollOptions o ON p.PollID = o.PollID
) AS Results
WHERE RowNum BETWEEN 1 AND 10
The query fails with an ' Invalid column name 'RowNum' ' error.
I have tried using 'Results.RowNum' but I get the same problem.
I don't understand what the issue is. The result set has a column headed 'RowNum' so why can't I apply a WHERE clause to this column? I can apply WHERE to the PollID column, for example, with no problem.
I have added some SQL to an Access form which updates the dbo_BM_Map table when the user hits the Apply button. There is a temp table with various fields, two being "Chapter_No" and "Initial_Mapping_Complete" which the update is based on.
I want this update to only apply to chapters that only have one name in the "Initial_Mapping_Complete" column. If a chapter has more than one then the update should ignore it. The attached screengrab shows you. The update should ignore chapter 19 as there are two people (Jim and James) in the Initial_Mapping_Complete field. Here is my code.
pdate dbo_BM_Map inner Join Temp_Progression_Populate on dbo_BM_Map.Product_ID = Temp_Progression_Populate.Product_ID Set dbo_BM_Map.Initial_Mapping_Complete = Temp_Progression_Populate.Initial_Mapping_Complete Where dbo_BM_Map.Chapter_No = Temp_Progression_Populate.Chapter_No And Temp_Progression_Populate.Initial_Mapping_Complete in (Select count(Initial_Mapping_Complete), Chapter_No from Temp_Progression_Populate Group by Chapter_No Having Count(Initial_Mapping_Complete) = 1)
My multiple level nested corelated query is not fetching correctresult. It work fine on small set of data, but fails on larger set ofdata. Any clue?Explaining data storing and discussing design would be tough for mehere, still to show you how complex I have created my life, here is thequery:select(SELECT Top 1 RowNSBranchID FROM AssoExtBranchToNSBranchMstM AM-- MMMWHERE AM.RowExtSysID IN(SELECT RowID FROM ExternalSystemMstM WHERE ExtSysID =(SELECT ExtSysID FROM ExternalSystemMstM WHERE SF = 'Active' ANDRowID =(SELECT MAX(RowID) FROM ExternalSystemMstM WHERE MCStatus = 2 ANDExtSysCode = UM.SystemCode)))AND RowExtBranchID IN(SELECT RowID FROM ExternalBranchMstMWHERE ExtBranchID =(SELECT ExtBranchID FROM ExternalBranchMstMWHERE ROWID =(SELECT RowID FROM ExternalBranchMstMWHERE ROWID =(SELECT MAX(ROWID) FROM ExternalBranchMstM WHERE MCStatus = 2 ANDExtBranchCode = UM.UpBranchCodeAND RowExtSysID IN(SELECT RowID FROM ExternalSystemMstM WHERE ExtSysID =(SELECT ExtSysID FROM ExternalSystemMstM WHERE SF = 'Active' ANDRowID =(SELECT MAX(RowID) FROM ExternalSystemMstM WHERE MCStatus = 2AND ExtSysCode = UM.SystemCode))))AND (SF = 'Active'))))AND AM.SF = 'Active'order by AssoID desc,TrackID desc) nsbranchid, UM.*fromTmpInProcessData062005MstM UM