GROUP BY With Multiple Fields

Jun 12, 2014

I have two issues I'm trying to deal with in my code.

1. I'm trying to group by first and last name, which are in two different columns
2. I'm trying to take an average of pay per miles.

Neither of these is working well. Actually, neither is working at all.

This is the code!

SELECT
OD.DriverID,
(W.FirstName + W.LastName AS 'Driver'),
DATEADD(dd,(DATEDIFF(dd,0,O.ReadyTimeFrom)),0) AS Date,
DATENAME(dw,O.ReadyTimeFrom) AS DayOfTheWeek,
Count(OD.OrderID) AS 'Total Orders',
SUM(O.Distance) AS OrderMiles,

[Code] ....

View 2 Replies


ADVERTISEMENT

Using An Expression To Group On Multiple Fields

Mar 23, 2008



I have an exisitng report that lists unit name, provider, runday, shift, patient. The report groups by unit name and there is a page break after each unit name. So in the current environment the report prints one page per unit that contains all of the providers, rundays, shifts, and patients for that unit name its grouping on. So the report would like like this when it prints:

Unit A
Provider 1 Runday 1 Shift 1





patient 1
patient 2
Provider 1 Runday 1 Shift 2





patient 1
patient 2
Provider 1 Runday 2 Shift 1





patient 1
patient 2
Provider 1 Runday 2 Shift 2





patient 1
patient 2
Provider 2 Runday 1 Shift 1





patient 1
patient 2
Provider 2 Runday 1 Shift 2





patient 1
patient 2
Provider 2 Runday 2 Shift 1





patient 1
patient 2
Provider 2 Runday 2 Shift 2





patient 1
patient 2
PAGE BREAK
Unit B............(repeat data from page 1)
PAGE BREAK
Unit C............(repeat data from page 1

The end user would like the ability to keep the report as is but would like to also be able to print the report as one page per each unit name, provider, runday and shift. so it would look like this

Unit A
Provider 1 Runday 1 Shift 1





patient 1
patient 2
PAGE BREAK
Unit A
Provider 1 Runday 1 Shift 2





patient 1
patient 2
PAGE BREAK
Unit A
Provider 1 Runday 2 Shift 1





patient 1
patient 2




So I created a boolean parameter with a prompt of Page break by Unit, Provider, Runday & Shift? My thought is if the users sets this to False, the report will group on just Unit Name (the first example). If the user sets this to True, the report will group on Unit Name, Provider, Runday & Shift.

I set the grouping expression for this data table as:
=iif(Parameters!Grouping.Value = "False", Fields!unit_Name.Value,(Fields!unit_Name.Value,Fields!Lname.Value,Fields!Rundays.ValueFields!Shift.Value))


Within the expression editor window it displays a syntax error and the report will not run.

Any help would be greatly appreciated!!!!!!!!!

View 7 Replies View Related

Transact SQL :: Get One Row From Multiple Based On Fields And Also Get Sum Of Decimal Fields?

Jul 2, 2015

I am using MS SQL 2012.  I have a table that contains all the data that I need, but I need to summarize the data and also add up decimal fields while at it.  Then I need a total of those added decimal fields. My data is like this:

I have Providers, a unique ID that Providers will have multiples of, and then decimal fields. Here are my fields:

ID, provider_name, uniq_id, total_spent, total_earned

Here is sample data:

1, Harbor, A07B8, 500.00, 1200.00
2, Harbor, A07B8, 400.00, 800.00
3, Harbor, B01C8, 600.00, 700.00
4, Harbor, B01C8, 300.00, 1100,00
5, LifeLine, L01D8, 700.00, 1300.00
6, LifeLine, L01D8, 200.00, 800.00

I need the results to be just 3 lines:

Harbor, A07B8, 900.00, 2000.00
Harbor, B01C8, 900.00, 1800.00
LifeLine, L01D8, 900.00, 2100.00

But then I would need the totals for the Provider, so:

Harbor, 1800.00, 3800.00

View 3 Replies View Related

Why Have To Group All Fields When Using MIN / MAX

Dec 18, 2012

Lets say I have a list of customers, order date, and an item they ordered. I want to grab the MIN order date by customer, and the associated product. If I do:

Code:
SELECT customer,min(order date),item
FROM mytable
GROUP BY customer

I get an error because item is not aggregated. But I don't want to group on it and i don't want to select a min/max of it. i just want it to carry over the item that is associated with that min order date.

View 8 Replies View Related

Group By Or Distinct - But Several Fields

Feb 11, 2014

How can I use a Distinct or Group by statement on 1 field when calling All or at least several ones.

Example:
SELECT id_product, description_fr, DiffMAtrice, id_mark, id_type, NbDiffMatrice, nom_fr, nouveaute
From C_Product_Tempo

And I want Distinct or Group By nom_fr

View 19 Replies View Related

How Do I Get Group By Fields As Column Name?

Mar 10, 2008

Dear experts,

Hi, please do give me your expert advise and opinon on this matter:

I have a table name PerformaceRecords with a few columns, one of which is performance banding.
i.e.
PerformanceBanding
------------
Outstanding
Good
Average
Good
Poor

When I use a group by clause, i.e. Select PerformanceBanding, Count(PerformanceBanding) as ResultCount from PerformanceRecords group by PerformanceBanding

I got the result as

PerformanceBanding ResultCount
---------------------------------
Good 2
Poor 1
Average 1
Outstanding 1

What I want to get is the PerformanceBanding as columns and the Result as rows

i.e.

Good Poor Average Outstanding
----------------------------------
2 1 1 1

how do I go about modifying my SQL select statement to achieve this result?

Thank you in advance for assisting me.

View 9 Replies View Related

Non Aggregated Fields In Group By Clause

Jul 8, 2013

I'd like to have all distinct recordIDs with relevant text associated with them. Each record has 3 text boxes in different languages. Each text in different language is defined by an AttributeDefinitionID. This is my query:

Select a.entryID, g.GroupName, c.CategoryName as ExperienceType,
e.AttributeValue as EnglishWording,
e1.AttributeValue as GermanWording,
e2.AttributeValue as RussianWording,
From Entry as a
inner join entrycategory as b on b.entryid = a.entryid

[Code] ....

but in the results I get additional rows for each record even if the record doesnt have all three text boxes populated and there is only EnglishText for example.

EntryID GrouPName EnglishWording GermanWording RussianWording
1586 Red abc NULL NULL
1586 Red NULL NULL NULL
3566 Yellow NULL Hallo Welt NULL
3566 Yellow NULL NULL NULL
3566 Yellow Hello world NULL NULL
3566 Yellow Hello world Hallo Welt NULL

1586 should only return the first line with English wording.
3566 should return the last line that shows both English and German wording populated

View 19 Replies View Related

Many Fields Update From A Group By Clause

Jul 20, 2005

Hi All,In Oracle, I can easily make this query :UPDATE t1 SET (f1,f2)=(SELECT AVG(f3),SUM(f4)FROM t2WHERE t2.f5=t1.f6)WHERE f5='Something'I cannot seem to be able to do the same thing with MS-SQL. There areonly 2 ways I've figured out, and I fear performance cost in both cases,which are these :1)UPDATE t1 SET f1=(SELECT AVG(f3)FROM t2WHERE t2.f5=t1.f6)WHERE f5='Something'and then the same statement but with f2, and2)UPDATE t1 SET f1=(SELECT AVG(f3)FROM t2WHERE t2.f5=t1.f6),f2=(SELECT SUM(f4)FROM t2WHERE t2.f5=t1.f6)WHERE f5='Something'Is there a way with MS-SQL to do the Oracle equivalent in this case ?Thanks,Michel

View 3 Replies View Related

Top N By Group -- Returning Additional Fields

Feb 18, 2008



I am looking to sum the dollar amounts spent by customer for their last five visits (actually looking for avg. spend in the last five trips).

So we are dealing with three fields: CustID, Date, Cost

I've had to do it the HARD way -- Crystal Report with running total fields numbering the five most recent trips (essentially rowID by group) and summing the $ figure; export to Access the entire report (1,000,000 records), and delete every record where the running rowID <> 5

There has to be a straightforward way to do this.


Any Top N query I've seen doesn't seem to be able to return a field other than the one sorting on. This is most annoying.

View 9 Replies View Related

Does The Group By Have To Include All Fields From The SELECT Clause?

Dec 3, 2007

hey all,

say i have the following function

SELECT GLF_CHART_ACCT.DESCR1, F1ADR_ADDRESS.ADDR1, F1ADR_ADDRESS.ADDR2,
F1ADR_ADDRESS.ADDR3, F1ADR_ADDRESS.ADDR_CITY, F1ADR_ADDRESS.ADDR_STATE,
F1ADR_ADDRESS.POST_CODE, F1ADR_ADDRESS.PHONE_NBR, F1ADR_ADDRESS.FAX_NBR,
F1ADR_ADDRESS.EMAIL_ADDR_NAME, F1ADR_ADDRESS.CONTACT_NAME,
F1ADR_ADDRESS.CONTACT_TITLE, GLF_CHART_ACCT.ACCNBRI, F1ADR_ADDRESS.ENTITY_UNIQUE_NBR

FROM GLF_CHART_ACCT

INNER JOIN F1ADR_ADDRESS ON (GLF_CHART_ACCT.CHART_NAME = F1ADR_ADDRESS.ENTITY_KEY1)
AND (GLF_CHART_ACCT.ACCNBRI = F1ADR_ADDRESS.ENTITY_KEY2)

GROUP BY GLF_CHART_ACCT.DESCR1, F1ADR_ADDRESS.ADDR1, F1ADR_ADDRESS.ADDR2,
F1ADR_ADDRESS.ADDR3, F1ADR_ADDRESS.ADDR_CITY, F1ADR_ADDRESS.ADDR_STATE,
F1ADR_ADDRESS.POST_CODE, F1ADR_ADDRESS.PHONE_NBR, F1ADR_ADDRESS.FAX_NBR,
F1ADR_ADDRESS.EMAIL_ADDR_NAME, F1ADR_ADDRESS.CONTACT_NAME, GLF_CHART_ACCT.ACCNBRI,
F1ADR_ADDRESS.CONTACT_TITLE, GLF_CHART_ACCT.CHART_NAME, F1ADR_ADDRESS.ENTITY_UNIQUE_NBR,
GLF_CHART_ACCT.SELN_TYPE1_CODE

HAVING CHART_NAME='ARCHART' AND GLF_CHART_ACCT.DESCR1 <> '' AND GLF_CHART_ACCT.SELN_TYPE1_CODE = 'Trade'
AND GLF_CHART_ACCT.DESCR1 LIKE '%" + Search + "%' ORDER BY GLF_CHART_ACCT.DESCR1;

I get errors if not all the fields are included in the group by clause.

what i dont get is why i have to create seperate groups for this query...or am i reading it wrong??

Cheers,

Justin

View 5 Replies View Related

Update Certain Fields In User Group Table With New Info

Apr 28, 2014

I've just written a query that successfully brings back the data from one table based on the information from another. Basically we have been given a table of information and need to update certain fields in our user_group table with the new info.

Here is the SELECT statement
SELECT user_group.id, user_group.name, user_group.description, Consultants.description AS Expr10, user_group.btype, user_group.rootmenu,
user_group.intra_user, user_group.primary_g_id, user_group.fname, user_group.lname, user_group.ntlogon, user_group.lang_id,
user_group.[external], user_group.title, user_group.work_tel, user_group.work_fax, user_group.work_ext, user_group.mobile, user_group.sex,
user_group.add2, user_group.add3, user_group.town, user_group.county, user_group.pcode, user_group.private_flag,

[code]....

We want to update the 'description' on the user_group table with the 'description' from the 'consultants' table. To test this, we only want to write the UPDATE so that it changes the description where the name is 'Adam Froth. The UPDATE statement that we've written is

UPDATE user_group
SET user_group.description = Consultants.description
FROM user_group
INNER JOIN Consultants
ON user_group.description = consultants.description
WHERE name like 'Adam Froth%'

but it keeps erroring and saying that it could 'Not be bound'.

View 2 Replies View Related

DB Design :: Partition With Single File Group Or Multiple File Group?

May 19, 2015

partition with single file group or multiple file group which one best.

we have some report running from partition table, few reports don't have any partition Key and after creating 400  partition  with 400 file group it is slow.what is best practices to crate  400 file group or single file group.

View 9 Replies View Related

T-SQL (SS2K8) :: Sequential Data Selection - Identify Different Fields Within A Group Of Records?

Jun 18, 2014

How to identify different fields with in a group of records?

Example:
create table #test
(ID int, Text varchar(10))
insert into #test
select 1, 'ab'
union all
select 1, 'ab'

[Code] ...

I want to show additional field as Matched as ID 1 has same Text field on both the records, and for the ID 2 I want to show Unmatched as the Text fields are different but with the same ID.

View 1 Replies View Related

Search Multiple Fields Using Like

Mar 2, 2007

I've done some simple sql's for searching a field using Like,But this one is different.
I am adding a param named @searchText
I would like to bring back all records in all the fields listedbelow that has that string in the field...
WHERE a.manufacturer = b.manufacturerIDAND a.location = c.locationIDAND a.Status = d.statusIDAND a.EquipmentType = e.IDAND a.calLab = f.ID AND a.testTechnology = g.id AND (c.locationID = @location OR @location = 0)
So, each line/field above I want to search for the string and includein the dataset.
Anyone can point me in the right direction?
Thanks,
Zath

View 7 Replies View Related

Dropdownlist With Multiple Fields

Sep 24, 2007

How can I get two fields to appear side by side in the DropDownList?  Ex.  FName and LName
 
Thanks

View 1 Replies View Related

Merging Multiple Fields

Mar 20, 2001

Please point me in the direction of a tutorial that will do help me do the following:

The database has been previously created and the users first & last names are in the respective columns. There is also a column that should contain the full name of the user but as such it only contains <NULL>. Is there a way to pull the first name and last name from the db then write both names to column3?

Thanks - Sharon

View 5 Replies View Related

Checking Multiple Fields At Once

Sep 29, 2005

I have a table that tracks some dates, and I am looking for an SQL statemet that will check all of the fields to see if a prespecified data range is true. For exampe you enter a start and end date and then then the SQL statement would check about 12 different fields to see if any of the dates are within that range. I am trying to use an or statement, but to no avail. So if you have any help it would be greatly appreciated.

View 1 Replies View Related

Getting Count With Multiple Fields

Sep 6, 2005

Hi all,I'm running into a road block, and I know I've done this before. I'mgetting fields from two tables, and I need to do a count of similaritems with it showing some extra info.Here's my fields:Log.LogId - IntLog.LogDispatcherID - IntOfficer.OfficerID - IntOfficer.OfficerFirstName - VarcharOfficer.OfficerLastName - VarcharI can get the info I need without a count with this:select a.LogID,a.LogDispatcherID,b.OfficerFirstname + ' ' + b.OfficerLastname as OfficerNamefrom[Log] a, Officer bwhere a.LogAssigned1 = b.OfficerIDBut when I try to add a count and group-by it errors out:select Count(a.LogID) as LogCount,a.LogDispatcherID,b.OfficerFirstname + ' ' + b.OfficerLastname as OfficerNamefrom[Log] a, Officer bwhere a.LogAssigned1 = b.OfficerIDGroup By a.LogIDI've done this before, but this isn't working. It's giving the error"it is not contained in either an aggregate function or the GROUP BYclause" for each field other then LogID.How can I do this? I want output similar to this:LogCountLogDispatchIDOfficerName334Tom Jones422John Smith.... EtcThanks for any suggestions or ideas...Sam Alex

View 2 Replies View Related

Updating Multiple Fields

Sep 22, 2005

How can I update each record in a table, based on a value in another tablewith a single SQL statement?For example, suppose I have the following two tables:Table1Name Something Color-----------------------------------------John GHAS BlueJohn DDSS BlueJohn EESS BluePaul xxxx RedRingo HJKS RedRingo FFFS RedSara hjkd PurpleSara TTHE PurpleJimi sdkjls GreenTable2Name Color------------------------John ?Paul ?Ringo ?Sara ?Jimi ?How can I update the color field in table 2 to correspond with the colorfield in table1 (so I can normalize the db and delete the color field fromtable1)?I know I could open table2 and loop through within my app; just wonderingabout a single SQL statement that would do it. I need a similar technique inother places as part of my app.Thanks,Calan

View 5 Replies View Related

Help ! Multiple Fields Using IN Condition....

Oct 27, 2006

Hi All,

I am trying to do something like this

Select * from Table 1 where (field1, field2, field3) IN (select field1, field2, field3 from table2 where fieldx = 'rt')

This can be done in oracle. Is there any equivalent in SQL Server ?

Can anybody please help !

Thanks.

PN

View 3 Replies View Related

Help ! Using Multiple Fields With IN Condition !

Oct 27, 2006



Hi All,

I am trying to do something like this

Select * from Table 1 where (field1, field2, field3) IN (select field1, field2, field3 from table2 where fieldx = 'rt')

This can be done in oracle. Is there any equivalent in SQL Server ?

Can anybody please help !

Thanks.

PN

View 3 Replies View Related

Inserting To Multiple Fields Using A Button

Jul 22, 2006

I have multiple textboxes in a page. How do i make them insert their values to multiple fields on multiple tables using a button.

View 1 Replies View Related

Possible To UPDATE Multiple Fields Conditionally?

Nov 14, 2013

I have a am doing some date calcs () . The situation is that I have a Move date (date a customer moved to a new home). I want to calculate their sales for the following 0-3 months after the move (month 0 being the move month). I have the month and year of the move (MthStart, YrStart), and I am adding 3 to MthStart to get the MthEnd of that 0-3 month period. I will then find sales BETWEEN YrStart&MthStart AND YrEnd&MthEnd (there is a YrMth field in the sales table)

Of course, for MthStarts 10, 11, and 12, the ends are 13, 14, and 15. So for these, I need to subtract 12, and increment the YrEnd by 1.

I am wondering if there is a way to update both the MthEnd and YrEnd fields at one time instead of separate SETs (or maybe I am just thinking about this the hard way to begin with). Is there a way to update both in a single CASE statement like WHEN MthEnd> 12 THEN MthEnd-12 AND YrEnd+1?

Code:
CREATE TABLE #myTable (
YrStart INT,
MthStart INT,
YrEnd INT,
MthEnd INT);

[code]....

View 4 Replies View Related

Aggregate With Multiple Fields Question

May 7, 2008

I'm having trouble using Aggregate functions with multiple fields.
Here is what I'm trying to do:

SELECT REPLACE(Cust_Key, sum(PRODUCT_CHARGE), count(Tracking_Number), Tracking_Number FROM Shipments = '2008-05-05'
Group By Cust_Key, Tracking_Number

I can get this to work when I use Group By for a single field like Cust_Key but I don't know how to make it work for multiple fields. What is the best way to write something that contains a few aggregate functions on top of multiple fields?

Thanks

View 4 Replies View Related

Using Multiple Fields As The Unique Identifier

Jun 10, 2008

Please see below post

View 2 Replies View Related

Multiple Updates And Identity Fields

Sep 27, 2006

I have a table used by multiple applications. One column is an Identify field and is also used as a Primary key. What isare the best practices to use get the identity value returned after an INSERT made by my code.. I'm worried that if someone does an INSERT into the same table a "zillionth" of a second later than I did, that I could get their Identity value.



TIA,



Barkingdog

View 4 Replies View Related

Transact SQL :: Concatenation Of Multiple Fields

Oct 29, 2015

I have the folloiwng fields:

ProbationLengthYears AS Decimal
ProbationLengthMonths AS Decimal
ProbationLengthDays AS Decimal

Sample Data:

ProbationLengthYears = 2.00
ProbationLengthMonths 0.00
ProbationLengthDays 0.00

I have successfully concatenated and converted all three fields into one field as Follow:

 SELECT
  CONVERT(varchar(10),CAST(cc2.ProbationLengthYears AS INT)) + ' Year(s)' + ' ' +
  CONVERT(varchar(10),CAST(cc2.ProbationLengthMonths AS INT)) + ' Month(s)' + ' ' +
  CONVERT(varchar(10),CAST(cc2.ProbationLengthDays  AS INT)) + ' Day(s)'

 The result is:

  2 Year(s) 0 Month(s) 0 Day(s)

Ideally I would like the result to be as follow because the probation months and days are 0:

  2 Year(s).

View 4 Replies View Related

Transact SQL :: Concatenate Multiple Fields Into One

Dec 5, 2015

I have a table where I need to concatenate all values into one field separated by a comma.  If the field is null display a blank value.  This is my table structure and example output

Create Table #read
(
id int
,field1 varchar(100)
,field2 varchar(100)
,field3 varchar(100)
,field4 varchar(100)

[code]...

View 5 Replies View Related

Concatenating Fields Over Multiple Rows

Jul 13, 2007

I have a query that produces seperate rows for people, but I want to combine them into one place. I tried doing this in SQL but apparently it's not very easy in SQL Server. You need to loop through a table using cursors. I'm not quite that advanced with SQL Server and was wondering if there might be an easier way just using SSRS.

In other words I have a table as such:

1 John Smith
2 Jane Doe
3 Matthew Jones

And I'd like to create one textbox that contains the following:

"John Smith, Jane Doe, Matthew Jones"

I've been drawing a blank. Anyone have any ideas?

Levi

View 4 Replies View Related

DTS Transformation Of Multiple Data In Single Fields

Jun 3, 2000

I have a very complex (for me, anyway) data transformation problem.

I've been given a flat-file of physician data from another system which must be automated for entry into the SQL server on a regular basis.

This was no problem until we discovered that several fields (all of which we wanted to use) had multiple pieces of information in them, separated by semicolons.

Well, this didn't seem to be too big of a problem, so I wrote a DTS activeX script to handle it. This is what I originally wrote:

'*******************
Function Transform()
'Declare variables
Dim strOffice
Dim strOfficeNew
Dim cChar
Dim x
Dim y
Dim z

'Scrub values into new rows
strOffice = DTSSource("Col050")
x = 1
y = len(strOffice)
z = 1

While x <= y
cChar = Mid(strOffice, x 1)
If cChar <> ";" Then
strOfficeNew = strOfficeNew & cChar
Else
DTSDestination("Phys_No") = DTSSource("Col001") DTSDestination("Addr_No") = z
DTSDestination("Addr_Office") = strOfficeNew
strOfficeNew = ""
z = z + 1
End If
x = x + 1
Wend

'Insert final record after last semicolon
If strOffice <> "" Then
DTSDestination("Phys_No") = DTSSource("Col001") DTSDestination("Addr_No") = z
DTSDestination("Addr_Office") = strOfficeNew
End If

Transform = DTSTransformStat_OK
End Function
'*********************

This, of course, didn't work. WHat I got was the last part of the parsed data, which for the first record, was the second Address in the field.

I searched around, and found the following script that is supposed to allow multiple rows off of a single row, but I can't seem to merge the two and still get the data out clean.

'**********
Dim nCounter
nCounter = 4

Function Main()

if nCounter > 0 then
Main = DTSTransformStat_SkipFetch
DTSDestination("PatientNumber") = DTSSource("PatientNumber") Select Case nCounter
Case 1
DTSDestination("PhysicianType") = "Admitting" DTSDestination("PhysicianId") = DTSSource
("AdmittingPhysician")
Case 2
DTSDestination("PhysicianType") = "Attending" DTSDestination("PhysicianId") = DTSSource
("AttendingPhysician")
Case 3
DTSDestination("PhysicianType") = "Referring" DTSDestination("PhysicianId") = DTSSource
("ReferringPhysician")
Case 4
DTSDestination("PhysicianType") = "Consulting" DTSDestination("PhysicianId") = DTSSource
("ConsultingPhysician")
End Select
nCounter = nCounter - 1
else
nCounter = 4
Main = DTSTransformStat_SkipInsert
end if
End Function
'**************

I'm not a VB Script expert, so there's probably something very simple that I'm missing here... if someone could point it out, I'd be greatly appreciative.

Jaysen

View 4 Replies View Related

How To Select Multiple Fields From A Joined Table

Mar 11, 2008

I have two tables - products and productpropertyvalue

I need to select multiple fields from the productpropertyvalue as it corresponds to the product id. The script I am using is

select a.id, a.productname, a.siteprice,
b.propertyvalue

from product a, productpropertyvalue b

where a.id = b.productid and propertyid=590

This allows me to extract only 1 propertyid. I need to make it add 3 other columns for propertyid=589, 617, 615

Any help solving this problem would be appreciated - thanx!

Ron

View 14 Replies View Related

Re-populate A Unique Number Into Multiple Fields

Oct 14, 2004

What I need to do is re-populate a unique number into multiple fields,

Let me explain, An employee can appear in the first table only once but can be in the second table multiple times with multiple employee numbers .There is a field called TFN that is unique and we are using it to create a unique id called KRid so what I have done is created 2 tables namely TEST_TBL and TEST2_TBL . In TEST_TBL I am populating a KRid with a unique no being produced by the TFN field only once i.e 12345 being the resulting unique id number. If an employee has 2 employee numbers i.e empno 1 and empno 1000,only employee no 1 will have the unique KRid created but nothing for 1000 because the record already exists , so what has me stumped is that the TFN for employee empno 1 and the TFN for empno 1000 are the same. How do I get the KRid (12345 from empno 1) to populate empno 1000 in TEST2_TBL , The second table has all records in so I can group the second table by TFN id but how do I populate employee 1000 in the second table with the KRid 12345.


Please help!!!!! Below are how the tables are set up and an example of the result.

TABLE 1

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TEST_TBL]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TEST_TBL]
GO

CREATE TABLE [dbo].[TEST_TBL] (
[Empl_Num] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Surname] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[First_Name] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Mid_Name] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Hours_Day] [numeric](18, 2) NULL ,
[Hours_Wk] [numeric](18, 2) NULL ,
[KR_ID] [bigint] IDENTITY (1, 1) NOT NULL ,
[TFN] [char] (32) COLLATE Latin1_General_CI_AS NULL ,
[Date_Term] [datetime] NULL ,
[Empl_Type] [int] NULL ,
[Cost_Centre] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Empl_Status] [int] NULL
) ON [PRIMARY]
GO

TABLE 2

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TEST2_TBL]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TEST2_TBL]
GO

CREATE TABLE [dbo].[TEST2_TBL] (
[EmpNumber] [char] (32) COLLATE Latin1_General_CI_AS NULL ,
[TFN] [char] (32) COLLATE Latin1_General_CI_AS NULL ,
[KR_ID] [char] (10) COLLATE Latin1_General_CI_AS NULL ,
[EmpStatus] [int] NULL ,
[EmpType] [int] NULL ,
[CommonName] [char] (32) COLLATE Latin1_General_CI_AS NULL
) ON [PRIMARY]
GO

Query goes as follows for table 1:

SELECT NPE000.EmpNumber, NPET00.RecordStatus, NPE000.KR_ID, NPE000.Surname, NPE000.FirstName, NPE000.SecondName, NPE000.Class, NPE000.DateEmployed, NPE000.DateOfBirth, NPE000.HoursPerDay, NPE000.HoursPerWeek, NPE000.PassportNo, NPE000.AwardCode, NPE000.EmailPayslipTo, NPE000.Location, NPE000.Grade, NPE000.DateTerminated, NPE000.EmploymentType, NPE000.DistCode, NPE000.EmpStatus, NPET00.TaxRefNo FROM NPE000 NPE000, NPET00 NPET00 WHERE NPET00.RecordStatus = 0 and NPET00.TaxRefNo <> ' 111111111' and NPET00.TaxRefNo <> ' 000000000' AND LENGTH(NPET00.TaxRefNo) >= 9 AND LENGTH(NPE000.KR_ID) >= 0 AND NPE000.EmpNumber = NPET00.EmpNumber


Query goes as follows for table 2:

SELECT NPE000.EmpNumber, NPE000.FirstName, NPE000.Surname, NPE000.Class, NPE000.Location, NPE000.EmploymentType, NPE000.EmpStatus, NPET00.TaxRefNo, NPE000.Paypoint, NPE000.KR_ID, FROM NPE000, NPET00 WHERE Recordstatus = 0 and (EmploymentType = 1 AND EmpStatus = 1 AND NPE000.EmpNumber = NPET00.EmpNumber


From this you can see that in table 1 it will only create 1 KR_ID for only one employee number but in table 2 I am bringing through all employee records. In table 2 I can group by NPET00.TaxRefNo which will bring all NPET00.TaxRefNo's togeather. From that I would like to populate the other employee numbers with the unique KR_ID.

Example:Table 1

000001,Jackson,James,Sam,7.6,38,12345,475431212


Example:Table 2

000001,Jackson,James,Sam,7.6,38,12345,475431212
001000,Jackson,James,Sam,7.6,38,,475431212

I hope this helps

Thanks in advance

View 10 Replies View Related

Pulling Data From Multiple Fields And Grouping

Jun 3, 2014

I have a table of Projects which have multiple Resources.

PROJ_ID, PROJ_NAME,RESOURCE1,RESOURCE2,RESOURCE3
01 Project1 001 005 088
02 Project2 002 004 005

How can I pull out a list of resources with the projects associated with them?

i.e. the above would return

001 01
002 02
004 02
005 01
005 02
008 01

or

001 01
002 02
004 02
005 01,02
008 01

View 10 Replies View Related







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