How do I go about subtracting adjacent Rows? Let's say each day I entered one row entry into a table (tblFlowerHeight)showing the new height of a flower in one column(Height)...say if I had a second second column (ChangeFromLastHeight), how would I go about showing the difference between current height and the last recorded height?
I am trying to eliminate a scalar function by rewriting a view. I currently have a structure similar to the following:
With FirstQuery as (SELECT Trial, SBOI, TBOI, FROM TU WHERE SBOI Between 22000 and 22999 and TBOI < 10000), strt as (SELECT TOP 1 TimeOfEvent, Trial, SBOI, TBOI From TU ORDER BY TimeOfEvent),
[Code] ....
What I trying to do is for the Trial, SBOI, and TBOI in FirstQuery, find the Start Time and Stop Time. TimeOfEvent is an integer in milliseconds. Say I have the following data:
TrialIDÂ Â Â Â SBOIÂ Â Â Â TBOIÂ Â Â Â TimeOfEvent AÂ Â Â Â Â Â Â Â Â Â Â Â 22000Â Â 5000Â Â Â Â Â 5 AÂ Â Â Â Â Â Â Â Â Â Â Â 22000Â Â 5000Â Â Â Â Â 10 BÂ Â Â Â Â Â Â Â Â Â Â Â 22000Â Â Â 5000Â Â Â Â Â 8 BÂ Â Â Â Â Â Â Â Â Â Â Â 22000Â Â 5000Â Â Â Â Â 15
So the DISTINCTÂ output would be:
    Trial    SBOI    TBOI    StartTime    StopTime     A        22000  5000     5                 10     B        22000  5000    8                 15
The problem I am having is that strt is selecting the smallest time period. It doesn't seem to care what the current record in cte is. I thought that by using my joins, it would make it select smallest TimeOfEvent for the Trial, SBOI, and TBOI that are selected in cte. Obviously that is not the case. So, I was trying to add a WHERE to the strt Select Statement such asÂ
WHERE TrialID = FirstQuery.TrialID and SBOI = FirstQuery.SBOI and TBOI = FirstQuery.TBOI but it isn't working either.
Hi,I am currently updating a column in my database table with the value typed into a text box. But it is updating with the new value, rather than taking away the value typed in from the present value of the column. 1. How would i subtract the value typed in away from the current column value?2. I guess I need to check the column value is above 0 before updating, then rebind the control to show new values after the update has happened, incase two people are using it at once. How would this be achived? Thanks for any help!!Jon P.S.My code is:private bool ExecuteUpdate(int quantity){ SqlConnection con = new SqlConnection(); con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True"; con.Open(); SqlCommand command = new SqlCommand(); command.Connection = con; TextBox TextBox1 = (TextBox)FormView1.FindControl("TextBox1"); Label labname = (Label)FormView1.FindControl("Label3"); Label labid = (Label)FormView1.FindControl("Label13"); command.CommandText = "UPDATE Items SET Quantityavailable = @qty WHERE productID=@productID"; command.Parameters.Add("@qty", TextBox1.Text); command.Parameters.Add("@productID", labid.Text); command.ExecuteNonQuery(); con.Close(); return true;} private bool ExecuteInsert(String quantity) { SqlConnection con = new SqlConnection(); con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True"; con.Open(); SqlCommand command = new SqlCommand(); command.Connection = con; TextBox TextBox1 = (TextBox)FormView1.FindControl("TextBox1"); Label labname = (Label)FormView1.FindControl("Label3"); Label labid = (Label)FormView1.FindControl("Label13"); command.CommandText = "INSERT INTO Transactions (Usersname)VALUES (@User)"+ "INSERT INTO Transactions (Itemid)VALUES (@productID)"+ "INSERT INTO Transactions (itemname)VALUES (@Itemsname)"+ "INSERT INTO Transactions (Date)VALUES (+DateTime.Now.ToString() +)"+ "INSERT INTO Transactions (Qty)VALUES (@qty)"+ command.Parameters.Add("@User", System.Web.HttpContext.Current.User.Identity.Name); command.Parameters.Add("@Itemsname", labname.Text); command.Parameters.Add("@productID", labid.Text); command.Parameters.Add("@qty", TextBox1.Text); command.ExecuteNonQuery(); con.Close(); return true; }protected void Button2_Click(object sender, EventArgs e){ TextBox TextBox1 = FormView1.FindControl("TextBox1") as TextBox; ExecuteUpdate(Int32.Parse(TextBox1.Text) );}protected void Button2_Command(object sender, CommandEventArgs e) { if (e.CommandName == "Update") { SqlDataSource1.Insert(); } }}
I'm in trouble. I have a table with some fields, one of them is an amount of money. One field indicates whether the amount is negetive or positive. This fields has only two possible values, 'N' and 'R'. 'N' means the amount is negative and 'R' means the amount is positive.
The problem I have is that I have to sum these amounts to give a total for each customer and report them as
customer1 total amount1 customer2 total amount2
I don't know how to make a query to bring these results. I know that sum would bring me the total amount for each customer but I don't know how to specify which fields are supposed to be negative so that it subtracts them instead of adding them.
By the way I'm not allowed to change the structure of the table.
hi all I want to find the set of rows that are present in result returned by first select statement & that are not there in the result of second select statement. Both select statement operate on tables having similar columns. Is there any way by which i can find such difference in results? Is this possible using EXCEPT function? plz help me.
I would like to know the best method or the simplest method to do the following. Take a datetime value and subtract a given number of hours. I am taking a UTC time and subtracting a given number or hours in a query. I seem to be getting mixed results.
One of the following selected fields is a sum. I need to subtract ISNULL(R.CMS_AMOUNT,0) where R.Waived = '1 from that amount. Pretty much just subtract those amounts where the waived field is 1. I am having trouble with the syntax. Can anyone help? Thanks.'
SELECT P.Efs_Network_ID , F.DBA_Name , F.ACCOUNT_STATUS , SUM(ISNULL(R.CMS_Amount,0)) - isnull(RA.Amount,0) AS Amount -- ?? isNULL(R.CMS_AMOUNT,0) WHERE R.Waived = '1' ??????
, isnull(SUM(RA.Pending),0) AS Pending , F.Salesman_no FROM tblPimsFDSLookup P INNER JOIN ACH_MerDemo F ON P.Efs_Network_ID = F.Efs_Network_ID LEFT OUTER JOIN tblrecovery R ON P.IntMid = R.IntMid LEFT OUTER JOIN( SELECT sum(isnull(Amount,0)) as amount , intmid , SUM(CASE WHEN RA.Status = 'P' THEN 1 ELSE 0 END) AS Pending FROM tblACHRecoveryAmounts RA --WHERE IntMid = 641046 WHERE RA.Status IN ('A','P','M','S') Group by intmid ) AS RA ON P.IntMid = RA.IntMid WHERE P.INTMID = @INTMID AND R.Waived = 0 AND Upgraded IS NULL GROUP BY P.Efs_Network_ID , F.DBA_Name , F.ACCOUNT_STATUS , RA.Amount ,F.Salesman_no
I need to write a SQL Query in which I have time1 and time2.
Now I need to find the difference between the time1 and time2 and if the difference is less then 15 minutes then I have to raise an Exception in SQL SERVER 2000.
If I have the total amount of 673000 that is passed as a parameter in my stored proc then, I need to do this:
Declare @TotalAmount money @TotalAmount = 673000 Col1 Col2 Col3 Test1 45 672955 --(I want to subtract 673000 from Col2 data) 673000-45 Test2 30 672925 --(I want to subtract 30 from the remaining amount of col3) Test3 100 672825 --(I want to subtract 100 from the remaining amount of col3)
I have a table for which I need a €œspecial€? running total. More specifically there should be a close communication between the credit and the debit column. The scenario should be in the following order
Credit
Debit
Balance credit
Balance debit
6
0
6
0
5
0
11
0
0
4
7
0
0
9
0
2
3
0
1
0
0
5
0
4
0
2
0
6 I have to point out that this is done in a grouped way where the CustormerID is the grouped clause. Now I have achieved this to a point where the calculations work only if the credit column is bigger than 0, but when the account starts with debit I get only sums of the column not the needed subtractions. What am I missing? Thanks in advance. DECLARE @PrevRunBal MONEY --Overall running total SET @PrevRunBal = 0 DECLARE @PrevGrpBal MONEY --Running total resets when account changes SET @PrevGrpBal = 0 DECLARE @PrevRunCnt INT --Overall running count (ordinal rank) SET @PrevRunCnt = 0 DECLARE @PrevGrpCnt INT --Running count resets when account changes SET @PrevGrpCnt = 0 DECLARE @PrevAcctID INT --The "anchor" and "account change detector" SET @PrevAcctID = 0 changes SET @PrevGrpBalP = 0 update Temp
SET --===== Running Total @PrevRunBal = RunBal = @PrevRunBal + Credit,
--===== Grouped Running Total (Reset when account changes) @PrevGrpBal = Bcredit = CASE
WHEN CustomerID = @PrevAcctID THEN CASE WHEN CREDIt > DEBIT or CREDIT = 0 THEN (@PrevGrpBal+CREDIT)-(DEBIT) WHEN DEBIT>CREDIT or DEBIT =0 THEN (@PrevGrpBal+DEBIT)-DEBIt END ELSE CASE WHEN CREDIT >DEBIT THEN (CREDIT) WHEN DEBIT > CREDIT THEN DEBIT -- restarts from 0 if only 1 rec. END
END,
--===== Running Count (Ordinal Rank) @PrevRunCnt = RunCnt = @PrevRunCnt + 1, --===== Grouped Running Total (Ordinal Rank, Reset when account changes) @PrevGrpCnt = GrpCnt = CASE WHEN CustomerID = @PrevAcctID THEN @PrevGrpCnt + 1 ELSE 1 -- Restarts count at "1" END,
--===== "Anchor" and provides for "account change detection" @PrevAcctID = CustomerID
I have a table CombinedSales script below (CreateCombSalesTable.sql) which contains the details of a sale.
A row in the table has two flags online/offline SalesAmount is the financial amount, online = 1 (online sales) online = 0 (combined sales off and online).
The table also contains the product and the client etc.,
What I am trying to do is subtract onlinesales from combinedsales within the query or outside I don't mind, to return the result as (below)
select skuid,SUM(SalesAmount),online,ClientName from t_CombinedSalesDetails where ClientName ='Asda' and SkuId = 200437 group by Skuid,Online,ClientName order by skuid
THIS is what I get below the online = 0 is the total sales of this product.
/****** Object: Table [dbo].[t_CombinedSalesDetails] Script Date: 27/08/2014 13:23:27 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON
I have a Column in my data that gives a financial period value in the YYYYMM format. i.e. an asset was re-valued in a particular period for example 201301. I need to find out the number(count) of periods(months) between another given period for example current period (201403) and the period provided in the table i.e. 201301.
I have a matrix which looks as follows: ----- Actuals | Budget ItemA 20 | 50 ItemB 45 | 30 ItemC 20 | 15
I would like to add a column with the difference between actuals and budget. Actuals/budget is 1 group in the matrix being the dimensionname. How can I calculate the difference (subtract actuals and budget), because if I just use the subtotal function it adds both totals together and I need to have the difference between them?
Hi all,I encountered this small problemI have two tables A and B with two columns 1 and 2 each, I would likethe first column of each table when match the first in the second tableis to subtract the second columnso the result would look as followsColumn 1 | Columnn 2where A1=B1 | A2-B2Now this is no problem so far ..But if there was no corresponding value in column 1 in either tables ..i.e. field A1 doesnt exist in Table B column 1, IT SHALL DO A2 - 0; or0-B2 ..NOW How can that be achieved ?Thanks all for your help
I have two date fields, start_date and end_date.I'd like to subtract the two dates, and come up with a number (thenumber of difference between the two dates).What function is there to do this? I haven't been able to find anythingin BOL.Start_date = 6/1/03End_date = 6/8/03End_date - start_date = 7*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
Hi there,I am trying to write a stored procedure in which I will retrieve SessionStartDate, SessionEndDate, and Duration (where Duration is calculdated by subtracting SessionEndDate from SessionStartDate).I was duration in the format of hours:minutes:seconds.The stored procedure is pasted below. I am getting the following error. Syntax error converting datetime from character string. Any ideas? ============================== CREATE PROCEDURE sp_ActiveSessions_UsersBrowsingDurationByDate_List ( @websiteID AS int = 0, @SelectedDateFrom AS dateTime, @SelectedDateTo AS dateTime) ASIF DateDiff(d,@SelectedDateTo,@SelectedDateFrom)=0begin set @SelectedDateFrom=null endIF ISNULL(@SelectedDateTo, '') = ''begin SET @SelectedDateTo = @SelectedDateFromendSET @SelectedDateTo = DATEADD(d, 1, @SelectedDateTo)SELECT UserID As 'User ID', SessionStartDate As 'Session Start Date', SessionEndDate AS 'Session End Date', ExitPageTitle As 'Exit Page Title', NumberOfPagesVisited As 'Number of Pages Visited', Convert(datetime, (CONVERT(DATETIME, SessionEndDate, 24) - CONVERT(DATETIME, SessionStartDate, 24)), 101) As 'Duration' FROM ActiveSessions WHERE UserID != 'Anonymous'GROUP BY SessionID, UserID, SessionStartDate, SessionEndDate, NumberOfPagesVisited, ExitPageTitleHAVING (min(SessionStartDate) BETWEEN @SelectedDateFrom AND @SelectedDateTo AND min(SessionEndDate) BETWEEN @SelectedDateFrom AND @SelectedDateTo)GO============================== <Columns> <asp:BoundColumn DataField="User ID" HeaderText="User ID"></asp:BoundColumn> <asp:BoundColumn DataField="Session Start Date" HeaderText="Session Start Date"></asp:BoundColumn> <asp:BoundColumn DataField="Session End Date" HeaderText="Session End Date"></asp:BoundColumn> <asp:BoundColumn DataField="Duration" HeaderText="Duration"></asp:BoundColumn> <asp:BoundColumn DataField="Number Of Pages Visited" HeaderText="Number Of Pages Visited"></asp:BoundColumn> <asp:BoundColumn DataField="Exit Page Title" HeaderText="Exit Page Title"></asp:BoundColumn> </Columns> ============================
Hello. How do I increment or decrement a date by adding/subtracting days? For example I want to add 4 days to the date today. I should get 07/31/2005 since today is 07/27/2005. And if I add 5 days then I should get 08/01/2005. Thank you.
JobRequirements (A) JobID int QualificationTypeID int
EmployeeQualifications (B) EmployeeID int QualificationTypeID int
Employee (C) EmployeeID int EmployeeName int
I need to return a list of all employees fit for a specific job ... The criteria is that only employees who have all the JobRequirements are returned. So if a job had 3 requirements and the employee had just 2 of those qualifications, they would not be returned. Likewise, the employee might have more qualifications than the job requires, but unless the employee has all the specific qualifications the job requires they are not included. If an employee has all the job qualifications plus they have extra qualifications then they should be returned...
How to only return those records where all the child records are present in the other table..
I am using sql server 2005. I stuck out in a strange problem. I am using view in my stored procedure, when I run the stored procedure some of the rows get skipped out means if select query have to return 10 rows then it is returning 5 rows or any other but not all, also the records displyaing is randomly coming, some time it is displaying reords 12345 next time 5678, other time 2468.
But if I run seperately the querys written in SP then it returns all the rows. Please give me solution why it is happening like this.
There are indexes in the tables.
Once I shrink the database and rebuild the indexes, from then this problem is happening. I have rebuild the indexes several time, also updated the statistics but nothing improving.
When expoting data from excel to sql server table, using SSIS package, after exporting is done, how would i check source rows are equal to destination rows. If not to throw an error message.
How can we handle transactions in SSIS 1. when some error/something happens during export and the # of rows are not exported fully to destination, how to rollback the transaction in SSIS.
I have a conditional split in an SSIS package - one split is where if rows are returned according to a specific rule, then insert those rows into to a Recordset Destinationm which points to a variable of Object type.
How I can use this variable to email fellow users. Â For example, what I would like is if ANY rows are returned to the Object variable (1 or more), then I would like to execute an email SP that we have on our server.
When expoting data from excel to sql server table, using SSIS package, after exporting is done, how would i check source rows are equal to destination rows. If not to throw an error message.
Hello, I have a survey (30 questions) application in a SQL server db. The application uses several relational tables. The results are arranged so that each answer is on a seperate row: user1 answer1user1 answer2user1 answer3user2 answer1user2 answer2user2 answer3 For statistical analysis I need to transfer the results to an Excel spreadsheet (for later use in SPSS). In the spreadsheet I need the results to appear so that each user will be on a single row with all of that user's answers on that single row (A column for each answer): user1 answer1 answer2 answer3user2 answer1 answer2 answer3 How can this be done? How can all answers of a user appear on a single row Thanx,Danny.
Hi i tried designing a SSIS package which loads only those rows which were different from existing rows in the table , i need to timestamp the existing row with an inactive date when a update of that row is inserted (ex: same studentID ) and the newly inserted row with a insert time stamp so as to indicate the new row as currently active, in short i need to maintain history and current rows in same table , i tried using slowly changing dimension but could not figure out, anyone experience or knowledge regarding the Data loads please respond.
example of Data would be like
exisiting data
StudentID Name AGE Sex ADDRESS INSERTTIME UPDATETIME 12 DDS 14 M XYZ ST 2/4/06 NULL 14 hgS 17 M ABC ST 3/4/07 NULL
New row to insert would be
12 DDS 15 M DFG ST 4/5/07
the data should reflect
StudentID Name AGE Sex ADDRESS INSERTTIME UPDATETIME 12 DDS 14 M XYZ ST 2/4/06 4/5/07
12 DDS 15 M DFG ST 4/5/07 NULL
14 hgS 17 M ABC ST 3/4/07 NULL
Please provide your input as much as you can even though it might not be a 100% solution.
I had created a trigger which sees that whether a database is updated if it is its copy the values of the updated row into another control table now I want to read the content of control_table into BIzTalk and after reading I want to delete it.Can any one suggest the suitable ay to do this?
I have the following variables VehicleID, TransactDate, TransactTime, OdometerReading, TransactCity, TransactState.
VehicleID is the unique vehicle ID, OdometerReading is the Odometer Reading, and the others are information related to the transaction time and location of the fuel card (similar to a credit card).
The records will be first grouped and sorted by VehicleID, TransactDate, TransactTime and OdometerReading. Then all records where the Vehicle ID and TransactDate is same for consecutive rows, AND TransactCity or TransactState are different for consecutive rows should be printed.
I also would like to add two derived variables.
1. Miles will be a derived variable that is the difference between consecutive odometer readings for the same Vehicle ID.
2. TimeDiff will be the second derived variable that will categorize the time difference for a particular vehicle on the same day.
My report should look like:
VehID TrDt TrTime TimeDiff Odometer Miles TrCity TrState 1296 1/30/2008 08:22:42 0:00:00 18301 000 Omaha NE 1296 1/30/2008 15:22:46 7:00:04 18560 259 KEARNEY NE
Running this code on my PC via VS 2005 .Net version 2.0.50727 on the server (shown in IIS) Code is in ASP.NET 2.0 and is a VB.NET Console application SSIS 2005
Problem & Info:
I am bringing in an Excel file. I need to first strip out any non-detail rows such as the breaks you see with totals and what not. I should in the end have only detail rows left before I start moving them into my SQL Table. I'm not sure how to first strip this information out in SSIS specfically how down to the right component and how to actually code the component to do this based on my Excel file here: http://www.webfound.net/excelfile.xls
Then, I assume I just use a Flat File Source coponent or something to actually take the columns in the Excel and split into an OLE DB Datasource to shove each column into a corresponding column in my SQL Server Table. I have used a Flat File Source in the past to do so with a comma delimited txt file but never tried with an Excel.
Desired Help:
How to perform
1) stripping out all undesired rows 2) importing each column into sql table