T-SQL (SS2K8) :: One Table Two Rows

Feb 4, 2015

What I want is to divide the row value for 'OB Dial Attempts' by the row value for '# Ready To Work Inventory', both in the same table.The code below will work, however I think there is a flaw in my logic. The actual table only has one row per category (MatrixCat) and will always have only one row per category.

CREATE TABLE #NumVals (MatrixCat VARCHAR(100), MatrixVal VARCHAR(100));
INSERT INTO #NumVals (MatrixCat, MatrixVal) VALUES
('# Ready To Work Inventory','606'),
('OB Dial Attempts','255');

[code]....

View 8 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Compare Rows In The Same Table?

Aug 7, 2014

We have a table setup to track changes that are made to another table, for auditing purposes. How do we compare the most recent record in the change table with the previous record in the change table? Particularly, we have a column named DUE_DATE in the change table and want to identify when the most recent change has a different DUE_DATE than the previous change made.

View 8 Replies View Related

T-SQL (SS2K8) :: Get Rows And Sum In Joined Table?

May 2, 2015

I want to return all rows in table giftregistryitems with an additional column that holds the sum of column `amount` in table giftregistrypurchases for the respective item in table giftregistryitems.

What I tried, but what returns NULL for purchasedamount, where I want purchasedamount to be the sum of the `amount` for THAT item, based on giftregistrypurchases.itemid=giftregistryitems.id:

SELECT (SELECT SUM(amount) from giftregistrypurchases gps where registryid=gi.registryid AND gp.itemid=gps.itemid) as purchasedamount,*
FROM giftregistryitems gi
LEFT JOIN giftregistrypurchases gp on gp.registryid=gi.id
WHERE gi.registryid=2

How can I achieve what I need?

Here's my table definition and data:

USE [tt]
GO
/****** Object: Table [dbo].[giftregistry] Script Date: 09-05-15 11:15:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[giftregistry](
[id] [int] IDENTITY(1,1) NOT NULL,

[code]....

Desired results:

purchasedamountidregistryidtitleogimgdescriptionURLamountpricecreatedate

[URL]

View 9 Replies View Related

T-SQL (SS2K8) :: Can It Change Columns Of A Table Values To Rows

May 14, 2014

I have a table with this info:

NrCard numberPersonAuto123456789101112
11111111111111111111User1VW Jetta6,46,46,46,45,825,825,825,825,825,825,826,4
22222222222222222222User2Honda CR-V 13,2113,2113,2112,0112,0112,0112,0112,0112,0112,0113,2113,21

How I can get this result:

NrCard numberPersonAutomonthvalue
11111111111111111111User1VW Jetta16,4
11111111111111111111User1VW Jetta26,4
11111111111111111111User1VW Jetta36,4
11111111111111111111User1VW Jetta45,82
11111111111111111111User1VW Jetta55,82
11111111111111111111User1VW Jetta65,82

[code]....

Should I use unpivot or pivot?

View 2 Replies View Related

T-SQL (SS2K8) :: Number Of Rows And Range For Each Partition In A Table?

Mar 13, 2015

Is it possible to show the number of rows and the range for each partition in a table ?

This shows me the range but not the row count per partition

SELECT sprv.value AS [Value], sprv.boundary_id AS [ID] FROM sys.partition_functions AS spf
INNER JOIN sys.partition_range_values sprv
ON sprv.function_id=spf.function_id
WHERE (spf.name=N'myDateRangePF')
ORDER BY [ID] ASC

View 4 Replies View Related

T-SQL (SS2K8) :: Send Multiple Rows With One HTML Table In Email?

Dec 2, 2014

I have a job below, which takes the results and send to the users in email.But I have a question, how can I send only one email with all rows, not to send the for every row on table separated email.

DECLARE @Body VARCHAR(MAX)
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
DECLARE @RowCountINT
DECLARE@idINT
declare@departmentnvarchar(30)

[code]....

View 2 Replies View Related

T-SQL (SS2K8) :: Check How Many Rows Delete Updated Per Day And Store It In Another Table?

May 8, 2015

how to track how many rows updated or deleted per day in a single table and load the information in another table .

View 7 Replies View Related

T-SQL (SS2K8) :: Delete All Rows Satisfying Certain Condition From Table A And Related Records From B And C

Apr 14, 2015

I have around 3 tables having around 20 to 30gb of data. My table A related to table B by a FK and same way table B related to table C by FK. I would like to delete all rows satisfying certain condition from table A and all corresponding related records from table B and C. I have created a query to delete the grandchild first, followed by child table and finally parent. I have used inner join in my delete query. As you all know, inner join delete operations, are going to be extremely resource Intensive especially on bigger tables.

What is the best approach to delete all these rows? There are many constraints, triggers on these tables. Also, there might be some FK relations to other tables as well.

View 3 Replies View Related

T-SQL (SS2K8) :: Write Into A Table User-entered Value And Increment That Number N Times As Existing Rows

Jun 25, 2014

I need to have a script where it ask the user for a value, the script will search for all records that match the value. Then it will display the numbers of records found and ask the user to enter a different value. The rest of the script will use this new value and increment by 1 n times as the number of records found. I started the script where it will ask for "HANDLE" and display the number of records found with that "HANDLE"

declare @HANDLE as varchar(30)
declare @COUNT as varchar(10)
declare @STARTINV as varchar(20)

set @HANDLE = ?C --This is the parameter to search for records with this value
set @STARTINV = ?C --User will input the starting invoice number
SELECT COUNT as OrderCount FROM SHIPHIST
where HANDLE = @HANDLE

I just can't figure out how to proceed to use the entered invoice # and increment by 1 until it reach the number of records found.

This will be the end results:

Count=5 --results from query
STARTINV=00010 --Value entered by user

Handle,Inv_Num
AAABBB,00010
AAABBB,00011
AAABBB,00012
AAABBB,00013
AAABBB,00014

View 9 Replies View Related

T-SQL (SS2K8) :: Rows Into Columns - Remove Duplicates And Variable Rows

Aug 5, 2014

I managed to transpose rows into columns.

;WITH
ctePreAgg AS
(
select top 500 act_reference "ActivityRef",
row_number() over (partition by act_reference order by act_reference) as rowno,
t3.s_initials "Initials"
from mytablestuff
order by act_reference

[code]...

But what I would love to do next is take each of the above rows - and return the initials either in one column with all the nulls and duplicate values removed, separated by a comma ..

ref, initials
Ag-4xYS
Ag-6xYS,BL
Ap-1xKW
At-2x SAS,CW
At-3x SAS,CW

OR the above but using variable number of columns based on the maximum number of different initials for each row.this is not strictly required, but maybe neater for further work on the view

ref, init1,init2
Ag-4xYS
Ag-6xYS,BL
Ap-1xKW
At-2x SAS,CW
At-3x SAS,CW

View 6 Replies View Related

T-SQL (SS2K8) :: Get Rows From C If Linked Rows In B Contain All Rows In A

Oct 28, 2014

I have 3 tables...

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..

View 5 Replies View Related

T-SQL (SS2K8) :: Get Version For Each Set Of Rows

Mar 20, 2014

In our concern, we have a table with lots of redundant rows, to avoid the redundant, we create some structure and denormalize the table now we need to migrate the old data into the new structure.

Here is my following table structure

DECLARE @TestTable AS TABLE(id INT, DAta1 VARCHAR(500), Data2 VARCHAR(500), Data3 VARCHAR(3))
INSERT INTO @TestTable
VALUES
(1, 'Name', 8, 1),
(1, 'possible Shifts', 30, 7),
(1, 'First shift', 22, 8),
(1, 'Second Shift', 24, 9),

[Code] ....

This is just a sample data we have a lot amount of data like this, any changes in Data1 or Data2 might came under a new version, any new insert or delete in a ID column based Set might consider as a new version. So I need to migrate this into the following structure of output

DECLARE @tbl AS TABLE (ID INT, DAta1 VARCHAR(200), DAta2 VARCHAR(200), Dversion INT)

I need to import the data as set with out redundant please do not consider the column data3, and the output might be like this

SELECT * FROM
(
VALUES
(1,'Name','8',1),
(1,'possible Shifts','30',1),
(1,'First shift','22',1),

[Code] ....

This is for single time import only...

View 9 Replies View Related

T-SQL (SS2K8) :: Rows To Column

Dec 29, 2014

Came across one scenario not able to find out how to do it..

Below is the table data

ColA
1
-1
2
-2

Need output in below way

ColA ColB
1 -1
2 -2

View 5 Replies View Related

T-SQL (SS2K8) :: Converting Rows Into Column

Apr 18, 2014

It is possible to covert rows into column by using tsql script, see attached file for more details...

CREATE TABLE Table1 (SalesOrder varchar(10), ItemName VARCHAR(100), Price INT, ItemNo int)
GO
INSERT INTO Table1
SELECT '01', 'Camera', 100, 1
UNION ALL
SELECT '01', 'Memory 4GB', 10, 2

[code]....

View 5 Replies View Related

T-SQL (SS2K8) :: Copy Rows Based On Value

Jun 22, 2014

Currently I have the below style data:

Name, StartPostion, EndPosition, Height

Person1, 10, 15, 5
Person2, 14,14,0
Person3, 20,21,1

What I am looking to do is, run through my table of data and create a record for each Name for each Position it takes up. For example

For Person1 the data will look like,

Name, StartPosition, EndPosition, Heigh, Position
Person1, 10,15,5, 10
Person1, 10,15,5, 11
Person1, 10,15,5, 12
Person1, 10,15,5, 13
Person1, 10,15,5, 14
Person1, 10,15,5, 15

View 8 Replies View Related

T-SQL (SS2K8) :: How To Return Zero If No Rows Found

Jun 25, 2014

I have a report that needs to return a count of zero for the rows that have no data, I have tried to use the Left Outer Join but my where clause is excluding the rows with no data and I need to filter the report with the Year, day and Month.

The date filters are from different table(dimDate), not sure how to include them in the #tmpOperationalTypes join as filters

ALTER PROCEDURE [dbo].[spcAdvancedComparisonDateDWReport]
@Year varchar(4000) = '',
@Day varchar(28) = '',
@Month varchar(28) = '',
@Locations varchar(4000) = '',

[Code] .....

View 9 Replies View Related

T-SQL (SS2K8) :: Compare Data Between 2 Rows?

Jun 27, 2014

I have the following recordset:

cmdBatchNbPdsLbsZONE
817159644 1.55320031
817159652 9.09590031
817159679 2.5891806
817159687 5.7123006
817159709 2.3903006
817159733 2.2792006
817159741 2.0647007
817159768 1.2430007
817159784 4.1547006
817159792 3.56576013

I need to extract the corresponding price from the following table:

Zone MaxWeight Price
---------------------- ---------------------------------------
31 1.70 7.14
31 2.20 8.76
31 3.30 9.47
31 4.40 9.69
31 5.50 10.61
31 6.60 11.05
31 7.70 11.49
31 8.80 11.93
31 9.90 12.37
31 11.00 12.81
31 12.10 13.23

In this case, the 2 first rows should give a price of

1) 7.14 (weight between 0 - 1.70)

2) 11.93 (weight between 8.80 - 9.90)

How can I do that with a query?

View 4 Replies View Related

T-SQL (SS2K8) :: Updating Multiple Rows

Jul 2, 2014

I need to update a empty column in our SQL database with the login ID for employees of our company.The table is called SY01200 and were I need to put the login ID is column INET5, and the login ID is just me stripping off the company's email address(removing the @company.com), and I need to update the INET5 column only where Master_Type = 'EMP'

And here is the Query that I am using to strip the email select LEFT(convert(varchar(40),EmailToAddress),LEN(convert(varchar(40),EmailToAddress))-14) As LoginName from sy01200 where Master_Type = 'emp'And here is what I thought the Query would be to update however I got and error saying more than 1 arguement returned

UPDATE sy01200
SET INET5 = (select LEFT(convert(varchar(40),EmailToAddress),LEN(convert(varchar(40),EmailToAddress))-14) As LoginName from sy01200 where Master_Type = 'emp')
WHERE Master_Type = 'EMP'

View 2 Replies View Related

T-SQL (SS2K8) :: Way To Convert Rows To Columns

Sep 17, 2014

I work with SQLite and need to write a query the old school way to convert rows to columns. If it was MS SQL I would use pivot to get the expected result. However this is SQLite I cannot use pivot.

Sample data:

create table t1 (id int, Dept char (1), Total int);
insert t1
select 1, 'A', 100
union
select 2, 'B', 120
union
select 3, 'C', 140
union
select 4, 'D', 150;

How do I use LEFT OUTER JOIN to produce result similar to the below?

SELECT 'Total' AS Dept,
[A], [B], [C], [D]
from

[code]....

View 7 Replies View Related

T-SQL (SS2K8) :: How To Compare Two Rows And Two Different Columns

Oct 22, 2014

I am fairly new to SQL and writing queries so bear with my faults. I am learning on the job, which is good and bad. Below is a query that I have written to obtain some information. The problem arises when we have a patient who goes from Patient Type '1' to Patient Type '2'. This needs to be considered a singular visit and the only way I can think that this may work is if: for any specific medical record a dsch_ts is equal to the Admit TS on the next row.

How to complete something like this and my google searches have been fruitless. I attached a spreadsheet with an example of what I am getting.

SELECT DISTINCT
TPM300_PAT_VISIT.med_rec_no,
TSM040_PERSON_HDR.lst_nm AS 'Last Name',
TSM040_PERSON_HDR.fst_nm AS 'First Name',

[Code] ....

View 6 Replies View Related

T-SQL (SS2K8) :: Updating Rows In Batches?

Nov 6, 2014

I have a production table with 400 million rows.

I have a staging table which has 48 million rows. This data is the same as the production data, except one column has a different value.

Create Table Production
(
Id Int Identity(1,1),
Code Varchar(20),
ReferenceSequence int
)

-- Staging Table

Create Table Staging
(
Code Varchar(20),
NewSequence int
)

I need to update the production table with the newSequence value from staging to replace the ReferenceSequence. I.e:

Update Production

Set ReferenceSequence = Staging.NewSequence
From Staging

where Production.Code = Staging.CodeHowever, updating 48 million rows at once will generate a lot of logging!

How can I do 1 million rows at a time, commit the changes then do the next million?

I've tried some of the examples on the following page [URL], but they look to just update the tables with the same values.

View 4 Replies View Related

T-SQL (SS2K8) :: Multiple Rows Into A Single Row

Nov 7, 2014

I am working with some old code that we are trying to clean up and perform some performance enhancements. The performance is now, so Very much better. From over 3 minutes to under 2 seconds.

But I am still trying to get the multiple rows into a single row. I would like to place this into a CTE to get the multiples into a single row. I just cannot get my head around how is the best, most efficient way to write the query.

This is a small example of what the rows look like in the resultset, and what I want to single to be.

DECLARE @BillingCorrect TABLE
(
ContractNumber char(10)
, pc1 int
, pb int
, om int
, vp int

[Code] ....

I am not sure how to write the query to have all the data in a single row.

View 2 Replies View Related

T-SQL (SS2K8) :: Find Same Combination Of Rows?

May 10, 2015

I have this data as below. I need to find out the combination from the data and take a count of them

CREATE TABLE A
( nRef INT,
nOrd INT,
Token INT,
nML INT,
nNode INT,
sSymbol VARCHAR(50),

[code].....

if you can see, the rows with column nRefNo 1 and 3 are same i.e. with same combination of Symbol viz. Silver and Castorseed.

Hence the desired output will be

Symbol Count
Castorseed-Silver 8

How to get this combination together and then take count of them. Please note i will be dealing with more than 5 million rows.

View 1 Replies View Related

T-SQL (SS2K8) :: Splitting Row Into Multiple Rows

May 14, 2015

I have a table that has for example data

I am looking to write a script that will change the first table into the second table.......

Table 1

Account No Name other field
1 Mr T and Mrs M Lambert xxx

I need to rewrite this as

Table 2

Account No split Name other field
1 a Mr T Lambert xxx
1 b Mrs M Lambert xxx

View 9 Replies View Related

T-SQL (SS2K8) :: How To Combine Results From 4 Rows Into 1

Oct 8, 2015

How can I get the results of this query>>

SELECT
RoleName = pr.name
,RoleType = pr.type_desc
,PermissionType = pe.state_desc
,Permission = pe.permission_name
,ObjectName = s.name + '.' + o.name

[Code] .....

WHICH RESULTS IN THIS>>

RoleNameRoleTypePermissionType PermissionObjectNameObjectType
publicDATABASE_ROLEGRANTDELETEdbo.AgencyUSER_TABLE
publicDATABASE_ROLEGRANTINSERTdbo.AgencyUSER_TABLE
publicDATABASE_ROLEGRANTSELECTdbo.AgencyUSER_TABLE

[Code] ....

View 3 Replies View Related

T-SQL (SS2K8) :: How To Repeat Columns Based On Rows

Mar 6, 2014

I have two columns which needs to repeat based on ID and number of distinct rows in that ID.

ID Date Created
1 1/1/2012 Sudheer
1 1/2/2013 Sudheer
1 3/3/2013 Sudheer
2 1/2/2014 Veera
2 2/5/2015 Veera

Results

ID Date Created Date Created Date Created
1 1/1/2012 Sudh 1/2/2013 Sudh 3/3/2013 Sudh
2 1/2/2014 Veera 2/5/2015 Veera

View 3 Replies View Related

T-SQL (SS2K8) :: Combining Multiple Rows Into One Row Per Employee

Apr 3, 2014

I'm working on a project where I need to retrieve employees data and then combine the data into single row per employee.

Sample Data:

WITH SampleData (PERSON, [DATA], [FIELD]) AS
(
SELECT 1234,'04/02/2014','Date'
UNION ALL SELECT 1234,'123','Department'
UNION ALL SELECT 1234,80.0,'Rate'
)
SELECT *
FROM SampleData;

The results from the above are as follows:

PERSONDATA FIELD
123404/02/2014Date
1234123 Department
123480.0 Rate

The desired results would be:

PERSONDate Department Rate
123404/02/2014 123 80.0

View 7 Replies View Related

T-SQL (SS2K8) :: Horizontal To Vertical Rows Conversion?

May 14, 2014

create table #temp1
(
col1 float,
col2 float,
col3 float,
clo4 float)
insert into #temp1 values (1.5, 1.6,1.7,1.8)
insert into #temp1 values (1.9, 1.0,1.2,1.8)

o/p should display as below is there a way we can do this with cte or some other option

col1 1.5 1.9
col2 1.6 1.0
col3 1.7 1.2
col4 1.8 1.8

View 1 Replies View Related

T-SQL (SS2K8) :: Report Non-existent Child Rows

Jul 3, 2014

I am trying to get a "Zero Values" report. The following code works except when there is no child row.

declare @m table
(
parcel char(1)
)
insert @m values ('A'), ('B'), ('C'), ('D'), ('E')
declare @v table

[Code] ....

I need the output to be:

B 0
D 0
E 0

View 5 Replies View Related

T-SQL (SS2K8) :: Ranking Rows On Basis Of SUM Of Records

Jul 17, 2014

Following is my table structure

IDRowCount PagID
1448
2267
3297
4216
5405
6254

[Code] ....

PageId is currently set to 0

I have a user input, @IntNoOfRowsPerPage = 800 Means 800 rows per page. So following is the output I require.

AIDRowCountPageId
1448 1
2267 1
3297 2
4216 2
5405 3
6254 3

[Code] ....

The values of PageID are such that summation of RowCount for PageID is <= @IntNoOfRowsPerPage (i.e, 800)

If NTILE function can be used in such scenarios.

View 5 Replies View Related

T-SQL (SS2K8) :: Dividing Two Rows Within CASE Statement

Jul 28, 2014

I was given the task to come up with a result set based on certain criteria:

Please add one row for each offer code

1) Opt-in rate by offer code: This can be calculated by dividing XXX Inventory with lead / XXX Inventory (A)

The report should read something like below:

Example result set:

Log Date: OfferLetter OfferCode DailyCount

2014-07-20 A XXX Inventory (A) 108
2014-07-20 A XXX Inventory with lead 54
2014-07-20 A XXX Inventory Opt-in Rate: 50%

There are 12 different groupings and OfferLetter A is just one of them.

Below is the code that is written to date:

DECLARE @Start datetime = DATEADD(day, DATEDIFF(day, 0, GETDATE() - 8), 0)
DECLARE @End datetime = DATEADD(day, DATEDIFF(day, 0, GETDATE() - 1) + 1, 0)
DECLARE @Today datetime = DATEADD(day, DATEDIFF(day, 0, GETDATE() - 1), 0);

SELECTDT.OfferCode, DT.OfferCodeDesc
INTO#tempOfferCodes

[Code] ....

The issue I'm having is that the values I need to divide by are in fact, a result set from the CASE statement. It's been a long time since I've done anything like this.

View 2 Replies View Related

T-SQL (SS2K8) :: Get Rows Based On Current Quarter

Sep 3, 2014

I am working on a report and the data source is Teradata. now I have situation where I want to get order id details based on the current quarter and year I am posting this same data. For TD related queries I do not where to post.

ACCT_ID ACCT_NMORD_NBRORD_DT ORD_AMT_USD
595709114ASDASD444447/28/2014 546
2224809440ASDASD444445/2/2012 546
1724031572ASDASD444446/22/2011 546
1702887651ASDASD444447/3/2014 546
1724020508ASDASD444447/16/2012 546
1148151895ASDASD444449/18/2013 546
2125154824ASDASD444449/2/2014 546
1503552723ASDASD4444412/20/2011 546
2224689808ASDASD4444410/4/2010 546
931387698ASDASD4444412/31/2010 546

View 4 Replies View Related

T-SQL (SS2K8) :: Getting Sum Values For Non Overlapping Rows By Datetime?

Oct 13, 2014

I want to count persons for non overlapping intervalls by room number. Here the data:

SET DATEFORMAT mdy;
DECLARE @PersonTime TABLE
(
ID INT,
Person INT,
Room INT,
Coming DATETIME,
Going DATETIME

[code]....

View 4 Replies View Related







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