Transact SQL :: Calculate Third Column Using Second Column And Variable

Nov 23, 2015

create table #t
(
id int,
col1 decimal(18,2)
)
go

[Code] ...

-- I want to subtract @X and col1. But my variable @X must be reduced for each value in col1 for each next row until it reaches zero.

-- OUTPUT:

-- id col1 col2
--@X at starting point is 15000
-- 1 5000.00 0 --@X IS 10000 = 15000 - 5000(col1)
-- 2 1000.00 0 --@X IS 9000 = 10000 - 1000
-- 3 10000.00 1000.00 --@X IS 1000 = 9000 - 10000
-- 4 12000.00 12000.00
-- 5 300.00 300.00
-- 6 35000.00 35000.00

--in col2 i just put zero where col1 is substract from @X and continue for every subsequent order.
-- in 3 row value is 1000 becouse @X is that big (1000 left from col1)

View 13 Replies


ADVERTISEMENT

Transact SQL :: Calculate DateTime Column By Merging Values From Date Column And Only Time Part Of DateTime Column?

Aug 3, 2015

How can I calculate a DateTime column by merging values from a Date column and only the time part of a DateTime column?

View 5 Replies View Related

Transact SQL :: Calculate SUM Of 100 Of EDSUM Column For EDCOST Column

Aug 18, 2015

How I can calculate the 'SUM of 100' of EDSUM column for EDCOST column. Every EDCOST should have sum of 100 on the calculation of EDSUM. I just want to know which is the EDCOST which has <>sum of 100.

Create table #sum (ED numeric, EDCOST numeric, EDName char(6), EDSum numeric, EDCode char(2))
Insert into #sum values (121, 2000,'HLMO',98,'DT')
Insert into #sum values (122, 2000,'HLMT',2,'DT')
Insert into #sum values (123, 2001,'HLMO',100,'DT')
Insert into #sum values (124, 2002,'HLMD',97,'DT')

[Code] ...

Expeced Output:
ED EDCOST EDName EDSum EDCode
126 2003 HLMR   98 DT
130 2005 HLMR   98 DT

View 7 Replies View Related

Transact SQL :: Calculate Column Purchasing Rate Per Customer For Product And Region

Oct 22, 2015

I have a table Product2 as the attachment at the bottom. Now i want to create a Column "Purchasing rate" over Product and Region like this. I tried some Code but it gave me still Error.

createtableProduct2
(
[product] [varchar](255),
[Region] [varchar](15),
[Subregion] [varchar](25),

[Code] ....

View 5 Replies View Related

Transact SQL :: SUM Of Two Table Column Base On Another Column Value And SUBTRACT And Join Tables

Oct 14, 2015

I have the following table

Table Name EmployeeInformation
EmployeeID EmployeeFirstName EmployeeLastName
    1             |John                       |Baker
    2             |Carl                        |Lennon
    3             |Marion                    |Herbert

Table Name PeriodInformation
PeriodID PeriodStart PeriodEnd
    1        |1/1/14      |12/30/14
    2        |1/1/15      |12/30/15

[code]...

I want a query to join all this tables based on EmployeeID, PeriodID and LeaveTypeID sum of LeaveEntitlement.LeaveEntitlementDaysNumber based on LeaveTypeID AS EntitleAnnaul and AS EntitleSick and sum AssignedLeave.AssignedLeaveDaysNumber based on LeaveTypeID  AS AssignedAnnaul and AS AssignedSick and subtract EntitleAnnaul from AssignedAnnual based on LeaveTypeID  AS AnnualBalance and subtract EntitleSick from AssignedSick based on LeaveTypeID  AS SickBalance

and the table should be shown as below after executing the query

EmployeeID, EmployeeFirstName, EmployeeLastName, PeriodID, PeriodStart, PeriodEnd, EntitleAnnual, AssignedAnnual, AnnualBalance, EntitleSick, AssignedSick, SickBalance

View 4 Replies View Related

Transact SQL :: Find Unique Rows In Column That Are Associated With Another Field In Another Column?

May 1, 2015

I am having issues trying to write a query that would provide me the unique GUID numbers associated with a distinct PID if the unique GUID's > 1.  To summarize, I need a query that just shows which PID's have more than one unique GUID. A PID could have multiple GUID's that are the same, I'm looking for the PID's that have multiple GUID's that are different/unique. 

Table1

GUID PID
GUID1 PID1
GUID1 PID1
GUID1 PID1
GUID2 PID1
GUID3 PID2
GUID3 PID2
GUID3 PID2

The result of the query would only have PID1 because it has two unique GUID's. PID2 would not be listed has it has the same GUID3 in each row.

Result:

PID1 

View 2 Replies View Related

Transact SQL :: Column Length Restriction When Naming CTE Column?

Jun 22, 2015

My CTE is failing and I don't know why...Is there a Common Table Expression column name length restriction???

View 2 Replies View Related

Transact SQL :: Distinct By One Column By Selecting Multiple Column?

Jul 17, 2015

I have a SQL Query issue you can find in SQL Fiddle

SQL FIDDLE for Demo

My query was like this

For Insert
Insert into Employee values('aa', 'T', 'qqq')
Insert into Employee values('aa' , 'F' , 'qqq')
Insert into Employee values('bb', 'F' , 'eee')
Insert into Employee values('cc' , 'T' , 'rrr')
Insert into Employee values('cc' , 'pp' , 'aaa')
Insert into Employee values('cc' , 'Zz' , 'bab')
Insert into Employee values('cc' , 'ZZ' , 'bac')
For select
select col1,MAX(col2) as Col2,Max(Col3) as Col3
from Employee
group by Col1

I supposed to get last row as 

    cc  Zz  bab

Instead I am getting 

  cc  Zz  rrr 

which is wrong

View 8 Replies View Related

Transact SQL :: Returning A Column Value Based Upon The Precedence Value Of Another Column?

Nov 4, 2015

#EMAIL_ADDRESSES which hold records similar to the following (CREATE code below):

View 6 Replies View Related

Transact SQL :: Get Table And Column Name In Separate Column Using PIVOT

Jul 16, 2015

Is there a way we can get Table and Column name in separate column using PIVOT or something?Right now what i have is:

Text                                                     QueryPlan             Plan_handle  
         Name         Value

select id,name,Address from person     <showPlznXML...   010101                 Table            Person
select id,name,Address from person     <showPlznXML...   010101                 column         id
select id,name,Address from person     <showPlznXML...   010101                 Table            Person

[code]....

View 26 Replies View Related

Transact SQL :: Select Row With Max (column Value) Group By Another Column

May 19, 2015

i dont't know how to select row with max column value group by another column. I have T-SQL

CREATE PROC GET_USER AS
BEGIN
SELECT T.USER_ID ,MAX(T.START_DATE) AS [Max First Start Date] ,
MAX(T.[Second Start Date]) AS [Max Second Start Date],
T.PC_GRADE,T.FULL_NAME,T.COST_CENTER,T.TYPE_PERSON_NAME,T.TRANSACTION_NAME,T.DEPARTMENT_NAME ,T.BU_NAME,T.BRANCH_NAME,T.POSITION_NAME
FROM (

[code]....

View 3 Replies View Related

Transact SQL :: Add Spaces To First Column So That Second Column Will Be Aligned

Sep 14, 2015

I want to add spaces (like space - len(col)) to first column so that second column will be aligned when exported to email (text).

DECLARE @ColumnSpaces TABLE (
 Col_1 VARCHAR(50),
 Col_2 VARCHAR(50)
 )
INSERT INTO @ColumnSpaces VALUES ('AAA', '123')
INSERT INTO @ColumnSpaces VALUES ('AAAAAAAAAAAAAAA', '123')

View 6 Replies View Related

Transact SQL :: XML Column Data Into Separate Column

Nov 18, 2015

I have a column with the data as below :-

<Items>
  <Item Value="Value1" />
  <Item Value="Value2" />
<Items>

How to get this data into seperate columns as 

Items
value1
value2

View 2 Replies View Related

Transact SQL :: Script One Column To Multiple Column?

Sep 29, 2015

I have below dataset and i want to convert as per my requirement.

Dataset:

In the above dataset, if i take 9/5/2015 then i should get like below,

View 10 Replies View Related

Calculate Column With Statement

Sep 19, 2013

I need to calculate column with statement like...

CostEventPrice
TicketSalesPrice (computed column)

If the CostEventPrice < 10,00$ then TicketSalesPrice = CostEventPrice + 2,00$
If the CostEventPrice between 10,00$ and 20,00$ then TicketSalesPrice = CostEventPrice + 3,00$
If the CostEventPrice > 20,00$ then TicketSalesPrice = CostEventPrice + 4,00$

View 7 Replies View Related

How To Calculate Only Total One Column

Jul 18, 2014

I want calculate to my total column sum

ex- col 1 col 2 col 3 col 4
raj 10 20 20
pani 20 88 88
tiger 87 78 89
john 77 77 77
---------
??
----------

View 1 Replies View Related

How To Calculate The Character Number In The Field Column

Apr 25, 2008



Hello:

I have a field hold varchar. I would like to calculate how many character in the field when user enter the data and save in the database.

Is there any way to do?

Thanks,

Snow

View 3 Replies View Related

Use Alias Name As A Column - Calculate Yearly Finance Values

Feb 25, 2014

I'm using this query to to calculate yearly finance values.

select [Year],[FinanceValue-2014],[FinanceValue-2013],[FinanceValue-2012],[FinanceValue- 2014]-[FinanceValue-2013] as [FinanceValue Variance]

Now I need to multiply the [FinanceValue Variance] * 2.50 and for that how can I use the alias name as column in the query. I tried this but it says invalid column name.

select [Year],[FinanceValue-2014],[FinanceValue-2013],[FinanceValue-2012],[FinanceValue- 2014]-[FinanceValue-2013] as [FinanceValue Variance], [FinanceValue Variance] * 2.50 as [NewVariance] from Finance

SumofVariance output will be like 5690.5893656 Also how can I show the SumofVariance to round off 4 decimal places like this 5690.5894.

View 1 Replies View Related

How To Calculate The Space (size In Bytes) Used By A BLOB Column In A Row

Dec 3, 2007

What is the easiest way to calculate the space (size in bytes) used by a BLOB column that is already stored in a particular row?

Thanks.

View 3 Replies View Related

Power Pivot :: Calculate Is Not Recognized When Adding A Column

Nov 3, 2015

I've been trying to use a simple calculate forumla when adding a column
CALCULATE(SUM([Credit]),
FILTER(ALL([Date],[Date]<=MAX([Date])))
or just a CALCULATE(SUM([Credit])

And I have always the same error

Calculate is not recognized. I've try it on PowerBI and Excel ...

View 2 Replies View Related

Calculate Total Tuition By Accumulating Column Values ( Loop?)

Jun 3, 2004

I am trying to create a procedure which will calculate the total tuition
This process involves 3 tables.
Contract table has tuition information which is all $100 (set price).
Discount table has discount type and discount percentage (ex. 0.3) on each discount type.
ContractDiscount table have contract number and discount number to connect both tables


I think I need to create a loop since some contract gets more than one discount.
I have to calculate and get result nee to be like this

total_tuition = (tuition - discountPer * tuition) - this has to be a loop condition

Do you have any suggestion ?

Thanks

View 3 Replies View Related

Transact SQL :: Selecting Rows As Column Name And Other Column Values As Rows

Jun 25, 2015

I have questions and answers from one table, I need to select questions as column names and answers column values as the results for the questions column.

View 28 Replies View Related

Reporting Services :: Unable To Calculate Running Balance Column Correctly In SSRS

Oct 7, 2015

I created a view that i want to use in ssrs.In the view there is a column for running balance.In the table contain transaction of inventory with their quantity.

"SELECT     TOP (100) PERCENT ITEMNMBR, TRXSORCE, DOCTYPE, DOCNUMBR, DOCDATE, HSTMODUL, UOFM, UNITCOST, EXTDCOST, TRXQtyInBase,
                          (SELECT     SUM(TRXQtyInBase) AS Expr1
                            FROM          dbo.INVTRXB AS b
                            WHERE      (DEX_ROW_ID <= a.DEX_ROW_ID) AND (ITEMNMBR = a.ITEMNMBR)) AS ENDQTY
FROM         dbo.INVTRXB AS a
ORDER BY ITEMNMBR, DOCDATE"

If i run the query on sql or use the view on ssr. The end qty is  not showing accurately.I ran it on another database it works perfectly. Then i noticed that the dex_row_ID of the second database is sequential as the date. But for the initial database it was not sequential as with the date.

View 4 Replies View Related

Integration Services :: Add New Column Based On Existing Column Using Derived Column Task?

Jul 28, 2015

I have a excel file which has a column called "Code" and their values are A,B,C,D,E,F,G,H.  I want to create a new column called "status" based on the values of "Code".

Code:

A
B
C
D
E
F
G
H

If A,C,E,G then "status" = "Active" else if  B,D,F,H then "Status" = "Inactive". I like to do it using "Derived Column".

View 4 Replies View Related

Transact SQL :: Alter Non Identity Column To Identity Column

Aug 12, 2009

when i alter non identity column to identity column using this Query alter table testid alter column test int identity(1,1) then i got this error message Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'identity'.

View 2 Replies View Related

How To Use A Variable As A Column Name?

May 25, 2008

 Hi, I want to use a variable and set it to column name but it just doesnt' workwhen I execute it. I got an error message "Invalid column name 'column1'. can you please help. ALTER PROCEDURE [dbo].[procedure_name]     @var1            INT = NULLAS    BEGIN        IF(@var1 = '-1')            BEGIN                --SET @var1 = column1            END    SELECT *    FROM table1    WHERE column1 = @var1   Thank you

View 4 Replies View Related

Column Name As Variable

Feb 25, 2001

Using a stored Procedure, I want to select a record from a Table if a certain string appears in a specified column, so I use

CREATE PROCEDURE spSearcher
@String varChar(20)
as
Select Column1, Column2, Column3 from Table1
where Charindex(@String1,Column1) > 0

which works fine.
But the following doesn't work:

CREATE PROCEDURE spSearcher
@String varChar(20)
@ColumnName VarChar(20)
as
Select Column1, Column2, Column3 from Table1
where Charindex(@String,@ColumnName) > 0


How can I substitute a variable for Column1, so I can pass the name Column1 or Column2, or Column3, as desired?

Thanks in anticipation,

Peter Caspersonn.

View 1 Replies View Related

Column As Variable

Jun 2, 2004

I have a problem that I'm sure is very simple to answer for anyone that knows a bit of T-SQL. In a stored procedure, I simply want to concatenate a string variable containing a column name into a Select statement.

For example:
I want to execute the following statement but using a variable for the column name:

Select * from tblmet1araw where JulianDay = 1


JulianDay is an integer
This is how I have my code set up:

declare @xxx as varchar(20)
set @theday = 'JulianDay'

select * from tblmet1araw where @theday = 1

I get the following error:
Server: Msg 245, Level 16, State 1, Line 4
Syntax error converting the varchar value 'JulianDay' to a column of data type int.

View 2 Replies View Related

Variable Column Name

Aug 11, 2006

Hi,

I have this query where I select data from the last 12 months (in 12 different columns).
What I would like to know is if it's possible to change the name of the columns to the month they refer to.

Thank's in advance,
AR

View 7 Replies View Related

Set Variable To Value In Column

Jul 26, 2007

Is it possible to set a variable in a stored procedure equal to avalue from a column when that column's respective ID is equal tomax(id)-1ID A B1 24 242 53 293 76 474 32 32What I am trying to do is update A in the last column to be equal to Bfrom the 4th row, plus A from the 3rd row. If I could set a variableequal to A in row 3 (in this case 76) I could easily add the variableto the existing value.I've tried something like this before. I'm sure some of you will sayright away, "of coarse that doesn't work". I'm new to sql.Set A = A + select( B from mytable where ID = (select (max(ID)-1) frommytable))where ID = (select (max(ID)) from mytable)ThanksMatt

View 1 Replies View Related

Get First Row First Column Value Into A Variable

Sep 28, 2006

It is my second time on this forum

Nice people managed to help me on my first thread. I am encouraged to proceed with you !

Well   I  have an Excel source that returns One row , two columns: what I want is get the value returned in  the first row - first colum into a variable so I can then execute sql tasks based on this filter parameter !

Can you guide me ? 

Regards Jacques

 

View 5 Replies View Related

Column Name As Variable

Oct 1, 2006

Greetings,

I have a table that contains various columns in it totalling 12,000 rows of data. For example;

site_ref, account_title, gl_code, period1, period2, period3 etc through to period12

I wish to write a query that will allow me to search for specific site_ref, acount_title etc and then only one of the period columns. This period column will be specified by the user at the time of submitting the query through reporting services. How do I assign a column to a variable so that the user can set it in the report parameters and then the code will run against that specific column for the period?

Example would be to see everything for site_ref = 'tb', account_title = 'gross rent' and the financial figures within the column titled 'period10' or the next time they run the report they may wish to run it against the values in period7.

Any pointers would be appreciated

Regards

View 4 Replies View Related

USING A VARIABLE AS A COLUMN NAME

May 28, 2008

I have a Windows programme using VS STudio 2005 / C# /Windows XP and

Microsoft.Practices.EnterpriseLibrary.Data

I am trying to pass an 'in parameter' to a stored procedure which will be used in the sp as a column name . The column names in the database are numbers (in this case, 0 to 45). I wish to pass the column name from my Windows programme tot he sp a and use it in the sp as the variable @BallColumnValue. Can anyone please advise me of the correct way to do this?

Thanking you in anticipation.

lpbcorp

Windows programme along the lines of:

else if (subsetList == false)

{

db.AddInParameter(dbUpdateBallSuccess, "BallColumnValue", DbType.Int16, i);

db.AddInParameter(dbUpdateBallSuccess, "BallNo", DbType.Int32, 1);

}

db.ExecuteNonQuery(dbUpdateBallSuccess);

Stored procedure is as follows:


USE [MyDatabaseName]

GO

/****** Object: StoredProcedure [dbo].[MyTableNameInsertMainDrawBallRecency;] Script Date: 05/22/2008 22:12:42 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE PROCEDURE [dbo].[MyTableNameInsertMainDrawBallRecency;]

(

@BallColumnValue nvarchar(10),

@Recency int,

@date DateTime,

@weeksSinceDrawn int,

@priorWeeksSinceDrawn int

)

AS

DECLARE lastrow_cursor CURSOR SCROLL FOR

SELECT CAST(@BallColumnValue AS COLUMN) FROM MyTableNameRecencyMainDrawBall

OPEN lastrow_cursor

FETCH LAST FROM lastrow_cursor INTO @weeksSinceDrawn

FETCH PRIOR FROM lastrow_cursor INTO @priorWeeksSinceDrawn

SELECT @priorWeeksSinceDrawn

IF @Recency = 0

BEGIN UPDATE AuMondayLottoRecencyMainDrawBall

SET [@BallColumnValue] = @Recency

WHERE Date = @date

END

ELSE

UPDATE MyTableNameRecencyMainDrawBall

SET [@BallColumnValue] = @Recency + @priorWeeksSinceDrawn

WHERE Date = @date



CLOSE lastrow_cursor

DEALLOCATE lastrow_cursor

View 10 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved