Is It Possible To Return Last Row Out Of Multiple Based On Row Index?
Jul 20, 2005
Here's what I'm trying to do:
I have a table, which I don't have administration over, with 4 interestingfields:
RecordCount - an auto incrementing primary key
CardNumber - integer
CompanyID - integer
AccessPriv - an string that varies constantly
There could be identical CardNumber's, but they must have differentCompanyId's. A data set might look like this:
RecordCount | CardNumber | CompanyID | AccessPriv
1 | 1 | 82 | all
2 | 2 | 82 | level 1
3 | 2 | 84 | all
4 | 1 | 82 | none
The table is transactional, so old records will not be flushed even thoughnew records contain the most current data (records 1 and 4 in this case). I'm wondering if there's a way to do a SQL SELECT query that, as it goesfrom the beginning to the end of the table, overwrites previous recordswhen later CardNumber's and CompanyID's match the previous records. So inthis case, the query would only return rows 2-4 because record 4'sCardNumber and CompanyID match record 1's.
I know this is possible with application logic, but is it possible with anSQL query?
Thanks.
View 4 Replies
ADVERTISEMENT
Jan 15, 2015
I want to return Order records which are one type and don't have the other type.
The issue is I have Orders with which has 2 distriubtion types .
Example
Order 12345 has Type S and Type X.
Order 67891 has Type S
I only want to return Order 67891 that are s Type and does not have type X
View 1 Replies
View Related
Dec 13, 2007
I've got a full text index working with a "CONTAINS" clause in the SQL. I'm looking for the character that I can place in CONTAINS(*,'WHATHERE') that will return everything. I've tried "*" and "%" but none of them will do it. Does anybody know?
Thanks
View 3 Replies
View Related
May 27, 2002
Hi,
I am making a program in Visual Basic .NET with SQL Server 2000.
I have a table "MyTable" with a primary key named "Id". The primary key is 'Create Unique' checked and 'Index' selected. When I insert all the fields required, except "Id" of course, I need the new record's "Id" in my VisualBasic program, but I don't know how...
I must do one of them, but don't know how either of them:
-Create a trigger on insertion that will send to the user that sended the insert command the "Id" of the record just created.
or
-get the command in Visual Basic that will send the Insert command with a return field ("Id")
Thanks in advance,
Sebastien Anselmo
View 6 Replies
View Related
Apr 29, 2008
Is their a way to return only a portion of a string returned from a query? Please look at the following query and what it Yields:
select UserName from MyDirectory
NTSRJoe MeekletonNTSRAnfreesa ClinklHeadBRYAmy KooplosaAKVermian Strikoos
How can I fix this query so that it returns everything to the right of the '' character?
So I want the query to instead return the following:
Joe MeekletonAnfreesa ClinklHeadAmy KooplosaVermian Strikoos
View 2 Replies
View Related
Jan 11, 2005
I'm storing records that contain a date/time data type. I am needing two links on a reports page (asp), the first should return all records for the current month and the second link should return all records for the last three months (including current month). I have no idea how to just sort by month.
I'm also not sure what to include here in this post to help you answer my question. On the form that is submitted initially the text field is named "txtSubmitDate" and in the database it's stored in a field called "submitdate" and is 8 characters in length.
I've tried:
'SELECT TODAY'S MONTH
SqlJunk = "SELECT * FROM eom WHERE MONTH(submitdate) = MONTH(GETDATE())-1"
'SELECT TODAY'S MONTH and the last 2 months
SqlJunk2 = "SELECT * FROM eom WHERE MONTH(submitdate) = MONTH(GETDATE()) OR MONTH(submitdate) = MONTH(GETDATE())-1 OR MONTH(submitdate) = MONTH(GETDATE())-2 ORDER BY submitdate ASC"
These are not working because it can't handle the change in year (going from january 2005 back to december 2004, etc).
Any ideas?
View 7 Replies
View Related
Aug 12, 2013
I have a database that has a table that contains basic demographics
•First_name
•Last_name
•Address
•City
•State
•Zip phone
•email
•dob
•etc
•etc
Contained in this table are a lot of duplicate names, and even different addresses. I would like to return an entire row of UNIQUE information based upon “first_name + last name”. Now I know just enough of sql to pull out unique first + last names, but not the entire row based upon this unique information.
View 5 Replies
View Related
Aug 3, 2015
I'm trying to return a query based on the dateadd function. I have a column in the database called date_added which is am successfully using the the DATEADD function above as date1. The Var1 variable I need to populate from the database too from a column called life_span which is an int data type. The error I get is An expression of non-boolean type specified in context where a condition is expected near select
My query is as follows: select guid, dateadd(day,life_span,date_added) as datepayday. From User_table
View 5 Replies
View Related
Aug 10, 2015
I have table that contains below data
CreatedDate ID Message
2015-05-29 7:00:00 AOOze abc
2015-05-29 7:05:00 AOOze start
2015-05-29 7:10:00 AOOze pqy
2015-05-29 7:15:00 AOOze stop
2015-05-29 7:20:00 AOOze lmn
and so on following the series for every set of same ID with 5 entries for each ID
I need to Find Maximum interval time for each ID and for condition in given message (between message like Start and Stop) I used below query and it works fine
select Id, max(CreatedDate) AS 'MaxDate',min(CreatedDate) AS 'MinDate',
DATEDIFF(second,min(CreatedDate),max(CreatedDate)) AS 'MaxResponseTimeinSeconds' from Table where Id in (
SELECT distinct Id
from Table
where Message like 'stop')
group by Id
Above query displays max response time for ID A00ze as 20 minutes, but stop message has occured at 7.15. I would need to modify the query to return max response time as 15 min(from 7.00 to 7.15).
Difference of starttime(where A00ze id started) and stoptime(where stop string is found in message).
View 7 Replies
View Related
Oct 24, 2007
Hi,
I have a package that I need to loop (possibly multiple times) based on a return value from a stored procedure.
I know that in DTS you could use the return value of "execution status" to do this.
Is there a way in SSIS to loop based on a return value?
Thanks much
View 5 Replies
View Related
Jun 15, 2007
I'm having some difficulty getting the appropriate results for my scenerio. I have two different datasets that I'm using. One is consisting of two joined tables and the other consisting of one sp. The sp's parameters rely on two things- one is the companyNum (inputed when the user runs the report) and two is the ContactNumType. The ContactTypeNum comes from the dataset of tables. I need to have a table consisting of this format:
ContactNumType1 (From the Tables)
File_Name1 (From the sp)
File_Name4 (From the sp)
File_Name3 (From the sp)
ContactNumType2 (From the Tables)
File_Name2 (From the sp)
File_Name7(From the sp)
ContactNumType3 (From the Tables)
File_Name5 (From the sp)
ContactNumType4 (From the Tables)
File_Name6 (From the sp)
File_Name10 (From the sp)
File_Name8(From the sp)
File_Name9 (From the sp)
So essentially what is going on is that every returned File_Name is grouped based upon the type of ContactNumType. My table returns the appropriate ContactNumTypes and the appropriate number of File_Names but returns only the first File_Name for each row. The File_Names should only grouped by the ContactTypeNums and each be unique. Is there any way to do that?
-------------------------------------------------------------------------------------------
Edited: I still am trying to work this out. I've tried a few run-arounds but none have worked. Adding custom code apparently is too risky at this point because of the security precautions that I've been instructed to take. Any help would be greatly appreciated as this project has been going on for days now....
View 3 Replies
View Related
Sep 3, 2014
I have data:
Ticket User Priority
A ME 1
B ME 1
C ME 2
C ME 3
D ME 2
E YOU 2
F YOU 1
G ME 3
H YOU 2
H YOU 3
I ME 1
Essentially if Ticket and User are the same I just want the min priority returned.
SO:
Ticket User Priority
A ME 1
B ME 1
C ME 2
D ME 2
E YOU 2
F YOU 1
G ME 3
H YOU 2
I ME 1
I've tried partition and rank but can't get it to return the right output.
View 5 Replies
View Related
Apr 30, 2015
We were asked to create an SQL function to return a unit price based on various criteria. The function works fine except for the tiered pricing (use of BillingPriceTable) calculation. What we need to do is break up the total quantity passed to the function and return the total of prices found. In our example, we passed a quantity of 9,721 units and need to return a total price of 231.92 using the table below.
Low Qty High Qty Fee Actual Qty Price
0 7500 0.025 7500 187.50
7501 15000 0.020 2221 44.42
Below is the table definition that we have to work with (ugghh).
CREATE TABLE [dbo].[BillingPriceTable](
[PriceTableID] [int] IDENTITY(1,1) NOT NULL,
[entity] [varchar](4) NULL,
[PriceTableCode] [varchar](10) NULL,
[PriceTableName] [varchar](40) NULL,
[Code] ....
What we have so far is shown below. The columns that start with bdxx are the "High Qty" values and the columns that start with prxx are the price for that quantity range. So, the current SELECT is shown below and it returns the price based on the entire qty of 9,721 and returns a unit price of 0.020 and should return 0.023857628
The current SELECT is shown below and is returning 0.020 which is the fee for the total rather than calculating the fee twice, once for the 0-7500 and again for the 7501-15000 (actually 7501-9721). Two things came to mind, one was a WHILE loop and the other was possibly a ranking function of some sort.
ALTER FUNCTION [dbo].[fn_GetPrice]
(
@plincdvarchar(3),
@pgrpcodevarchar(4),
@pitmcodevarchar(4),
@qtydecimal(10,1) = 1,
@corpnbrvarchar(9)
)
[Code] ....
View 9 Replies
View Related
Mar 20, 2007
We are using SQL2005.
I have a stored proc that runs a Select query based on a complex view.
The sproc has two input date parameters (StartDate and EndDate).
We are experiencing SQL timeout problems when the sproc is run with certain Start and End Dates.
We have run the SQL Profiler and created a trace (trc) file (We've used the 'Default' trace configuration).
We have used the trace file in SQL Server Management Studio to try and automatically create indexes on some of our tables.
Unfortunatly SQL Server Management does not make any index recommendations.
I think we are not capturing the right information in our trace file to allow SQL Server Management Studio to do its job.
How do I use SQL Profiler to capture a trace of my sprocs query, so that it can be used by SQL Server Management Studio, to recommend index changes?
Any help appreciated.
Reagrds,
Paul.
View 1 Replies
View Related
Jun 11, 2007
I upsized an access database with a key / index on ordernumber and linenumber.
However if I open the table in the Management Studio the records aren't ordered this way (same goes for select * from table) I get:
Ordernumber
Linenumber
200724001
37
200724004
3
200724006
33
200724001
3
200724011
19
200724014
5
200724006
37
200724011
19
200724006
28
Same goes for my crystal reports files, since the records aren't ordered by ordernumber / linenumber all my formulas go bezerk..
Am I wrong thinking the records should be ordered according to the prim. index?
Please help because I don't want to have to change all my 40+ reports to include an "ORDER BY"
Best regards,
Mike
View 7 Replies
View Related
Nov 24, 2015
I created composite clustered index key based on Gender and Salary column
The Query executed Successfully and <g class="gr_ gr_135 gr-alert gr_tiny gr_spell undefined ContextualSpelling multiReplace" data-gr-id="135" id="135">i</g>
got composite index key id Gender(-), Salary I <g class="gr_ gr_310 gr-alert gr_gramm undefined Grammar only-ins replaceWithoutSep" data-gr-id="310" id="310">want</g> know why Gender(-) display like this?
And Gender is <g class="gr_ gr_391 gr-alert gr_spell undefined ContextualSpelling ins-del multiReplace" data-gr-id="391" id="391">nvarchar</g> (20)
View 2 Replies
View Related
Oct 2, 2007
I need to call the stored procedure below. Basically what I need to know is if the query returns a record?
Note I would be happy if I could just return the number Zero if no records are returned. Can someone please help me out here?Here is my query so far in SQL Server. I just don't know how to return a value based upon the result of the records returned from the query.
GOCREATE PROCEDURE [dbo].[GetNameStatus]( @CountryId decimal, @NameId decimal, @DescriptionId decimal)AS SELECT Name.Active FROM Name INNER JOIN NameDescription ON Name.NameId = NameDescription.NameId WHERE Name.CountryId=@CountryId AND Name.NameId=@NameId AND NameDescription.DescriptionId=@DescriptionId AND Name.Active='Y'
View 3 Replies
View Related
Jul 23, 2005
Hello-I'm fairly new to writing SQL statements and would greatly appreciatesome help on this one.I'm working on a project for a non-profit that I volunteer for. Partof the database tracks membership using tables like this:PersonInfo-------------------PersonID (primary key)FirstNameLastNameetc..PeopleMemberships-------------------PPLMembershipIP (primary key)PersonIDMembershipTypeIDFeePaidMembershipTypes--------------------MembershipTypeID (primary key)MembershipYearStandardFeeMembershipDescription (varchar)Just because a person is in PersonInfo, doesn't mean they have anythingin PeopleMemberships (they can be in the databse for other reasons andnot have or have ever had a membership).Membership fees vary by year and type of membership and they want toretain a history of a person's memberships.What I'm looking to do here is write a query (a view in SQL Server)that will return the following InfoPersonID, MostRecentMembershipYear, FeePaidForThatMembership,DescriptionOfThatMembershipI'm thinking that I'd use max(MembershipYear), but that requires groupby for the other columns, so I'm getting all of the people'smemberships returned.I'm pretty sure this can be best done with a subquery, but I'm not surehow.Can someone please point me in the right direction or provide a samplethat I can learn from?Kindly,Ken
View 4 Replies
View Related
Jul 22, 2015
I have 2 tables each containing a material type. Table 1 contains material from their 3D application. Table 2 contains material with specific values that is not ours and we cannot rename or edit the data. I need a type of junction or mapping table that can connect the user material to the preset material. for example:
User Material = Wood-MDF
Preset Material = MDF Panel
I figured that i would make this table with 3 fields (ID, UserMaterialID, PresetMaterialID).How would i then construct a query view / Stored procedure that would return the Preset data values based on the user material id?
View 2 Replies
View Related
Jun 23, 2015
Goal: My request is the retrieve the return result from sp_Test as 8, 2, 4, 1 ,3 (take a look at picture 1) based on the chronological list from User-Defined Table Type dbo.tvf_id.
Problem: When I execute the stored procedure I sp_Test I retrive the list that is from 1 to 8. I don't know how to do it?
Information: I'm using SQL server 2012
create table datatable (id int,
name varchar(100),
email varchar(10),
phone varchar(10),
cellphone varchar(10),
none varchar(10)
);
insert into datatable values
[Code] .....
View 2 Replies
View Related
Nov 6, 2015
I have a table where hours are being loaded in a weekly basis. The YearWeek is populated when the data is loaded. The value format of the Year Week is 2015-39, 2015-41, etc. I need to calculate the total hours per Fiscal Year.For example, week '2015-39' will be return FY15 and week '2015-41' will return FY16, and so on. By extracting the year, I can do a group by and have total hours for each year.
Currently, I have it working by splitting the value into year and week and then looping through each year and week, so I can assign the totals to the corresponding FY.select sum(hours) as total, yearweek from tablename group by yearweek...Then I loop through using C#.I can return the FY using an actual date,how to do it for year-week format for any given year.
select CASE
WHEN CAST(GETDATE() AS DATE) >
SMALLDATETIMEFROMPARTS(DATEPART(YEAR,GETDATE()),09,30,00,000)
THEN
DATEPART(YEAR,GETDATE()) + 1 ELSE DATEPART(YEAR,GETDATE())
END AS FY
View 9 Replies
View Related
Sep 10, 2015
As part of analyzing our fire department's response times, we measure the time it takes to get a certain amount of people on a fire scene. I have two table that contains incident data. The incident table contains one row per incident. The apparatus table contains multiple rows per incident with each row contain the information for each unit. They are connected by the incident key with a one to many relationship.
The column apparatus.num_personnel contains the count of personnel for each fire truck. The goal is to capture the response time of the unit that is carrying the 10th person to the scene. In the example below, E78 was the unit that the sum of apparatus.num_personnel was => 10. There response time of 0:06:18 is returned to the incident table.
I realize I will need to create a logical test (calculated column on the incident table) that sums the number of personnel for each incident and then when that number => 10, then return the MIN Response Time of that row. From past projects, I understand I can create a temporary table (ADD COLUMNS) which will iterate over each incident row, comparing the units for that incident. I"m just not sure how to put it all together.
Overview of data model. The incident and apparatus are my data tables and the rest are lookup tables. The parameter table is used for a percentile measure, but doesn't play a role with this project.
View 9 Replies
View Related
Jun 2, 2004
I have a situation where I need two values (both are integers) returned from a stored procedure. (SQL 2000)
Right now, I use the statement "return @@Identity" for a single value, but there is another variable assigned in the procedure, @NewCounselingRecordID that I need to pass back to the calling class method.
I was thinking of concatenating the two values as a string and parsing them out after they are passed back to the calling method. It would look something like "21:17", with the colon character acting as a delimiter.
However, I feel this solution is kludgy. Is there a more correct way to accomplish this?
Thanks in advance for your comments.
View 2 Replies
View Related
Apr 19, 2006
I can not get a multiple row resultset to display or even get sent to my client application running on coldfusion.
What is the problem with the code?
How do i display and return a resultset to my coldfusion client application?
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
ALTER PROCEDURE dbo.nTransaction
(@pAccountNo varchar(30), @N int, @ntransCursor CURSOR VARYING OUTPUT, @nValue varchar(4000) OUTPUT)
AS
set @N = 0
SET ROWCOUNT @N
SET @ntransCursor = CURSOR FOR
-- FORWARD_ONLY STATIC
SELECT CONVERT(varchar,Eh.EntryID), Eh.EntryReference,E.AccountNo, E.Narrative, E.Amount, Eh.EntryDate
FROM entryheaders as Eh cross join entrys as E
WHERE Eh.EntrySerial = E.EntrySerial and AccountNo = @pAccountNo
ORDER BY Eh.EntryID DESC
SET ROWCOUNT 0
OPEN @ntransCursor
WHILE (@@FETCH_STATUS = 0)
BEGIN
FETCH NEXT FROM @ntransCursor into @nValue
END
CLOSE @ntransCursor
DEALLOCATE @ntransCursor;
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
Pls i need urgent help!!!
View 2 Replies
View Related
Jun 19, 2007
searched all over, couldn't find a solid answer...is it possible to return multiple values from a sql function with sql server 2005?
e.g., I want to do this:
select id, data, whatever, dbo.fnMyFunction(id, whatever) from table
and have the output have columns (id, data, whatever, col1, col2) where col1 and col2 are returned by fnMyFunction
possible? easier way? thanks in advance...
View 4 Replies
View Related
Mar 20, 2014
I'm working on a query that is asking to return data on dependents which a person can have 0-many, in a single row but sep columns. The dependent data I need to include are Dep First Name, Dep Last Name, Dep Relationship.
So my result should look something like this:
EEID| DepFirstName| DepLastName| DepRelationship| DepFirstName| DepLastName| DepRelationship
121 Billy Larson Spouse Alison Larson Child
How do I do this with SQL?
View 1 Replies
View Related
Oct 8, 2014
I’m trying to return data in a single row.Here’s what my table looks like:
Employee #,Hours Type,Total Hours
1234,Regular,40
1234,OT,8
1234,Regular,36
[code]....
I need the results of my query to total each hours type and group together:
EmpNo,Sum Of Regular, Sum of Overtime,Sum of Doubletime
1234,76,19,12
7777,45,8,5
I don’t know how to get the data returned in a single row.
View 2 Replies
View Related
Sep 12, 2007
I am getting multiple rows returned because the form that am working with has 4 possible different signtures on it I need to be able to get it so that I can return on row with the a column for the signature and date for each signature
SELECT a.op__docid,
a.order_no, a.deptname, a.order_date, a.person_completing, a.date_req, a.dept_head, a.dept_head_ext,
a.deliver_to, a.vendor_info, a.purchase_reason, a.qty1, a.qty2, a.qty3, a.qty4, a.qty5, a.item1, a.item2,
a.item3, a.item4, a.item5, a.unit_cost1, a.unit_cost2, a.unit_cost3, a.unit_cost4, a.unit_cost5,
a.ext_cost1, a.ext_cost2, a.ext_cost3, a.ext_cost4, a.ext_cost5, a.shipping, a.total,
b.op__tiername, b.op__sectionid, b.op__usersigname, b.op__when,
CASEIF a.op__docid IN (SELECT op__parentid FROM t4w_signatures WHERE a.op__docid = op__parentid AND op__sectionid = 386) AS Requestor,
CASEIF a.op__docid IN (SELECT op__parentid FROM t4w_signatures WHERE a.op__docid = op__parentid AND op__sectionid = 385) AS DeptHead,
CASEIF a.op__docid IN (SELECT op__parentid FROM t4w_signatures WHERE a.op__docid = op__parentid AND op__sectionid = 384) AS Administration,
CASEIF a.op__docid IN (SELECT op__parentid FROM t4w_signatures WHERE a.op__docid = op__parentid AND op__sectionid = 444) AS Receiver
FROMfd__purchase_order a
JOINt4w_signatures b
ON a.op__docid = b.op__parentid
View 1 Replies
View Related
May 22, 2007
Hi there,I have tables with such structuretransaction_YYMM(idx,date,company_id,value)where YYMM stands for 2digits year and monthI want to define query (maybe view, procedure):select * from [???] where date>='2007-01-01' and date<='2007-04-30'which will grab data fromtransaction_0701transaction_0702transaction_0703transaction_0704and return all as onebest regardsRafal
View 3 Replies
View Related
Feb 21, 2008
Hello,
Any help would be greatly appreciated. I have a single row that looks like this.
Cust, Add, Item, Value
1 ST 258 6
I want to return six rows based on the value and the value could be any number.
All of the row information will stay the same except the Value that will count off of the original value.
Cust, Add, Item, Value
1 ST 258 1
1 ST 258 2
1 ST 258 3
1 ST 258 4
1 ST 258 5
1 ST 258 6
View 3 Replies
View Related
Nov 14, 2007
hi can anyone please help me
i have a stored procedure ,can i put the value of this into a variable......????
I have one more query ---how can i pass the multiple values returned by this stored procedure into a single variable ...
example if my stored procedure is
[dbo].[GetPortfolioName](@NT_Account varchar(100) )
and ans of this are
NL
UK
IN
GN
JK
then how can i put this into a variable like
Declare @PortfolioName as varchar(250)
set @PortfolioName =(exec ].[GetPortfolioName](@NT_Account) )
.......
and my ans is
@PortfolioName = 'NL','UK','IN','GN','JK'
now can i make a function which returns 'NL','UK','IN','GN','JK'
View 1 Replies
View Related
Nov 9, 2006
Hi,
I'm trying to retrieve some records from an SQL database.
I've a table named CustomerOrder with three fields - custID , productname and quantity
No keys in the table. it's row based approach. every custID can have multiple entries for different products.
Example:
CustID ProductName Quantity
1 Product1 2
1 Product2 3
2 XXX 1
2 Product1 2
1 Product3 4
I would like to write a query that gives the result as follows :
CustID ProductName Quantity
1 Product3 4
2 Product1 2
Meaning that, query has to retrieve only one record per custID based on highest quantity.
select custId,Productname,quantity from customerorder where quantity = (select max(quantity) from customerorder)
the above query returns only one record. (ofcourse..)
Kindly help me to get the desired.
Thank You.
View 5 Replies
View Related
Mar 11, 2008
I have read a lot in favor and recommendation of returning multiple resultsets.
But now I have to implement it with a scenario.
I have a Parent Table named "Books" and a Child one named "Volumes".
A book can have multiple volumes.
Now I want to display the list of Books with their Volumes pagewise.
How can I implement that procdure.
View 3 Replies
View Related