"Insert Into Select" writing to table but contains sub-query reading from same table - sql

I am adding records into my table "SampleTestLimits" using an "Insert Into Select", but which also has a sub-query reading from the same table to perform a count for me.
I don't think the sub-query is seeing the earlier records added by my "Insert Into Select". It's the same for Oracle and SQL Server. The code for SQL Server is shown below (my sub-query begins with "SELECT COALESCE...").
I have another stored procedure which does work in a similar situation.
Would appreciate it if anybody could tell if what I'm doing is a no no.
ALTER PROCEDURE [dbo].[CreateSampleTestLimits]
#SampleCode as NVARCHAR(80),
#TestPosition as smallint,
#TestCode NVARCHAR(20),
#TestVersion smallint,
#EnterDate as integer,
#EnterTime as smallint,
#EnterUser as NVARCHAR(50)
AS
BEGIN
INSERT INTO SampleTestLimits
([AuditNumber]
,[LimitNumber]
,[ComponentRow]
,[ComponentColumn]
,[ComponentName]
,[TestPosition]
,[SampleCode]
,[AuditFlag]
,[LimitSource]
,[LimitType]
,[UpperLimitEntered]
,[UpperLimitValue]
,[LowerLimitEntered]
,[LowerLimitValue]
,[LimitTextColour]
,[LimitPattern]
,[LimitForeColour]
,[LimitBackColour]
,[CreatedDate]
,[CreatedTime]
,[CreatedUser]
,[LimitText]
,[FilterName]
,[deleted]
,IsRuleBased)
SELECT 1 --starting auditnumber
,(SELECT COALESCE(MAX(LimitNumber), 0) + 1 AS NextLimitNumber FROM SampleTestLimits WHERE SampleCode=#SampleCode AND TestPosition=#TestPosition AND ComponentRow=1 AND ComponentColumn=1 AND AuditFlag=0) -- TFS bug# 3952: Calculate next limit number.
,ComponentRow
,ComponentColumn
,(select ComponentName from TestComponents TC where TC.TestCode=#TestCode and TC.ComponentColumn=TestLimits.ComponentColumn and TC.ComponentRow = TestLimits.ComponentRow and TC.AuditNumber=TestLimits.AuditNumber)
,#TestPosition
,#SampleCode
,0 --auditflag
,1 --limitsource = test
,[LimitType]
,[UpperLimitEntered]
,[UpperLimitValue]
,[LowerLimitEntered]
,[LowerLimitValue]
,[LimitTextColour]
,[LimitPattern]
,[LimitForeColour]
,[LimitBackColour]
,#EnterDate
,#EnterTime
,#EnterUser
,[LimitText]
,[FilterName]
,0 --deleted
,0 --rule based
FROM TestLimits join Tests on Tests.TestCode=TestLimits.TestCode and Tests.AuditNumber= TestLimits.AuditNumber WHERE Tests.TestCode=#TestCode and Tests.auditnumber=#TestVersion and ([TestLimits].FilterString is null or DATALENGTH([TestLimits].FilterString)=0)
END

Assuming that I understand your logic correctly (ie. that you want the nextlimitnumber to increase by 1 for each row being added), in Oracle, I'd do it by using the analytic function row_number() to work out what number to add to the previous max value, something like:
INSERT INTO sampletestlimits (auditnumber,
limitnumber,
componentrow,
componentcolumn,
componentname,
testposition,
samplecode,
auditflag,
limitsource,
limittype,
upperlimitentered,
upperlimitvalue,
lowerlimitentered,
lowerlimitvalue,
limittextcolour,
limitpattern,
limitforecolour,
limitbackcolour,
createddate,
createdtime,
createduser,
limittext,
filtername,
deleted,
isrulebased)
SELECT 1, --starting auditnumber
(SELECT COALESCE (MAX (limitnumber), 0) + 1 AS nextlimitnumber
FROM sampletestlimits
WHERE samplecode = p_samplecode
AND testposition = p_testposition
AND componentrow = 1
AND componentcolumn = 1
AND auditflag = 0)
+ row_number() over (partition by testposition, componentrow, componentcolumn, auditflag) as nextlimitnumber, -- TFS bug# 3952: Calculate next limit number.
componentrow,
componentcolumn,
(SELECT componentname
FROM testcomponents tc
WHERE tc.testcode = p_testcode
AND tc.componentcolumn = testlimits.componentcolumn
AND tc.componentrow = testlimits.componentrow
AND tc.auditnumber = testlimits.auditnumber),
p_testposition,
p_samplecode,
0, --auditflag
1, --limitsource = test
limittype,
upperlimitentered,
upperlimitvalue,
lowerlimitentered,
lowerlimitvalue,
limittextcolour,
limitpattern,
limitforecolour,
limitbackcolour,
p_enterdate,
p_entertime,
p_enteruser,
limittext,
filtername,
0, --deleted
0 --rule based
FROM testlimits
JOIN tests
ON tests.testcode = testlimits.testcode
AND tests.auditnumber = testlimits.auditnumber
WHERE tests.testcode = p_testcode
AND tests.auditnumber = p_testversion
AND ( testlimits.filterstring IS NULL
OR datalength (testlimits.filterstring) = 0);
I had to guess at what the partition by clause would need to contain - adjust that as necessary for your requirements.

Related

How to calculate superscript values in SQL

I have prices coming in my source file like below -
78-22¼,
78-18⅝
I need to calculate these price. For example for first case result should be 78-22.25. I searched a lot but found that SQL supports few of these characters only. Is there anyway to make sure we are able to calculate for whatever value we are getting. Solution in either SQL or PowerShell could work.
You could write a PowerShell function to convert the fractions to decimals:
PS ~> ConvertTo-Decimal '18⅝'
18.625
To do so, we'll need to write a function that:
Uses regex to identify and extract the integer and fraction parts
Uses [char]::GetNumericValue() to get the decimal representation of the fraction
Outputs the sum of the two
function ConvertTo-Decimal {
param(
[Parameter(Mandatory)]
[string]$InputObject
)
if($InputObject -match '^(-?)(\d+)(\p{No})?$'){
$baseValue = +$Matches[2]
if($Matches[3]){
$baseValue += [char]::GetNumericValue($Matches[3])
}
if($Matches[1] -eq '-'){
$baseValue *= -1
}
return $baseValue
}
return 0
}
Hoo this one was fun.
If you want to do it purley in TSQL give this a tug:
DECLARE #table TABLE (Glyph NVARCHAR(2), Dec DECIMAL(8,6))
INSERT INTO #table (Glyph, Dec) VALUES
(N'¼', 1.0/4),(N'½', 1.0/2),(N'¾', 3.0/4),(N'⅐', 1.0/7),
(N'⅑', 1.0/8),(N'⅒',1.0/10),(N'⅓', 1.0/3),(N'⅔', 2.0/3),
(N'⅕', 1.0/5),(N'⅖', 2.0/5),(N'⅗', 3.0/5),(N'⅘', 4.0/5),
(N'⅙', 1.0/6),(N'⅚', 5.0/6),(N'⅛', 1.0/8),(N'⅜', 3.0/8),
(N'⅝', 5.0/8),(N'⅞', 7.0/8),(N'⅟', 1.0/1)
DECLARE #values TABLE (ID INT IDENTITY, value NVARCHAR(20))
INSERT INTO #values (value) VALUES
(N'78-22¼'),(N'78-18⅝'),(N'10+1')
;WITH sort AS (
SELECT v.*, t.*,
CASE WHEN m.value = v.value THEN
CASE WHEN t.Dec IS NOT NULL THEN REPLACE(p.value,t.Glyph,'')+dec
ELSE p.value
END
ELSE
CASE WHEN t.Dec IS NOT NULL THEN REPLACE(m.value,t.Glyph,'')+dec
ELSE m.value
END
END AS v,
CASE WHEN m.value = v.value THEN '+'
ELSE '-' END AS op,
ROW_NUMBER() OVER (PARTITION BY v.value ORDER BY CASE WHEN m.value = v.value THEN CHARINDEX(m.value,v.value) ELSE CHARINDEX(p.value,v.value) END) AS subID
FROM #values v
OUTER APPLY STRING_SPLIT(v.value,'-') m
OUTER APPLY STRING_SPLIT(v.value,'+') p
LEFT OUTER JOIN #table t
ON RIGHT(CASE WHEN m.value = v.value THEN p.value ELSE m.value END,1) = t.Glyph
)
SELECT ID, value, SUM(v * CASE WHEN subId = 1 THEN 1 WHEN op = '+' THEN 1 ELSE -1 END) AS v
FROM sort
GROUP BY ID, value
ID value v
---------------------
1 78-22¼ 55.750000
2 78-18⅝ 59.375000
3 10+1 11.000000
#values replaces your table.
disclaimer: this works, it'll probably perform like hot garbage, but it works :P
In T-SQL you could write a function like this that takes a vulgar fraction and replaces it with its decimal equivalent (this is not completely exhaustive, but handles the most common fractions, and makes a guess about whether you want .666 or .667 or something else for ⅔):
CREATE FUNCTION dbo.FractionToDecimal(#str nvarchar(255))
RETURNS TABLE
AS
RETURN
(
SELECT str = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(REPLACE(REPLACE(REPLACE(#str, N'¼','.25'),
N'½','.5'), N'¾','.75'), N'⅓','.333'), N'⅔','.666'),
N'⅛','.125'), N'⅜','.375'), N'⅝','.625'), N'⅞','.875')
);
Sample usage:
DECLARE #x table(str nvarchar(255));
INSERT #x VALUES(N'78-22¼'),(N'78-18⅝');
SELECT [input] = i.str, [output] = o.str
FROM #x AS i
CROSS APPLY dbo.FractionToDecimal(str) AS o;
Output:
input
output
78-22¼
78-22.25
78-18⅝
78-18.625
Working example in this fiddle.
Note there are only so many fraction codes available that you could be pulling in ... so you could add any to the above e.g. from this set but it isn't the case that you would have to handle any possible fraction, only the ones that are represented by these specific symbols. If someone passes in plain text 9/10 or 31/33 that is a completely different problem space than what you have outlined in the question.

MERGE statement for SCD type 2 is creating duplicate rows?

I have the below MERGE statement that I built to implement SCD type 2 on my SQL Server DB however if you look at the attached image, this sometimes inserts multiple duplicate rows which is incorrect - this should be one latest row per meterkey/meterserialnumber.
Is there anything obvious in the code I need to amend? It's weird because if I add a test row of data and run the merge, this works fine.. its just the occasional rows where it seems to be doing this.
DECLARE #DateNow int = CONVERT(INT, CONVERT(VARCHAR(8), GETDATE(), 112))
IF Object_id('tempdb..#meterkeysinsert') IS NOT NULL
DROP TABLE #meterkeysinsert;
CREATE TABLE #meterkeysinsert
(
MeterKey int,
change VARCHAR(10)
);
MERGE INTO [DIM].[MeterDetails] AS Target
using dbo.test AS Source
ON Target.meterkey = source.meterkey
and target.MeterSerialNumber = Source.MeterSerialNumber
and target.islatest = 1
WHEN matched THEN
UPDATE SET Target.islatest = 0,
Target.todatekey = #Datenow
WHEN NOT matched BY target THEN
INSERT ( meterkey
,[MeterSerialNumber]
,[lguf]
,[electricityMetertype]
,[profileType]
,[timeSwitchCode]
,[lineLossFactorId]
,[standardSettlementConfiguration]
,[energisationStatus]
,[DateSpecifiedKey]
,[distributorId]
,[gspid]
,[FromDatekey]
,[ToDatekey]
,[IsLatest])
VALUES (Source.meterkey
,Source.[MeterSerialNumber]
,Source.[lguf]
,Source.[electricityMetertype]
,Source.[profileType]
,Source.[timeSwitchCode]
,Source.[lineLossFactorId]
,Source.[standardSettlementConfiguration]
,Source.[energisationStatus]
,Source.[DateSpecifiedKey]
,Source.[distributorId]
,Source.[gspid]
,#Datenow
,NULL
,1 --IsRowCurrent
)
output Source.meterkey,
$action
INTO #meterkeysinsert;
INSERT INTO [DIM].[MeterDetails]
(MeterKey
,[MeterSerialNumber]
,[lguf]
,[electricityMetertype]
,[profileType]
,[timeSwitchCode]
,[lineLossFactorId]
,[standardSettlementConfiguration]
,[energisationStatus]
,[DateSpecifiedKey]
,[distributorId]
,[gspid]
,[FromDateKey]
,[ToDateKey]
,[IsLatest])
SELECT A.MeterKey
,[MeterSerialNumber]
,[lguf]
,[electricityMetertype]
,[profileType]
,[timeSwitchCode]
,[lineLossFactorId]
,[standardSettlementConfiguration]
,[energisationStatus]
,[DateSpecifiedKey]
,[distributorId]
,[gspid]
,#Datenow
,null
,1
FROM dbo.test a
INNER JOIN #meterkeysinsert CID
ON a.MeterKey = CID.Meterkey
AND CID.change = 'UPDATE'
`

In memory queries using SQL Server

I'm afraid that even though I am using CTE's in my query, that maybe, behind the scenes, a lot of disk caching is going on -- so it may as well not be using CTE's.
The whole point of using CTE's was that my original query code was way too slow, and would eventually get a transport level error and crash.
Well, it's still too slow. Maybe even slower. I don't know yet.
Is there a way to tell SQL Server to go ahead and be resource hog for my query?
I am only guessing, but I think it is using disk space to cache memory results. When I look at task manager memory utilization, I see SSMS at 161 MB. SSMS is where I am running the query from.
Here is my code - you don't have to read it in detail, but in brief, the source table contains about a million rows.
I need a solution, so alternative ideas are welcome...
WITH MetEdFliers AS
(
SELECT DISTINCT
[CustomerName1], [Mailing_Address], [Mailing_Address2], [Mailing_Zip]
FROM
[dbo].[_MetEd_Detail]
WHERE
RunId = (SELECT RunId FROM LastLoadRuns WHERE UtilityId = 9)
AND [Profitable] = 1 -- and not low income, should flag exist
),
MetEdLookUpFirst AS
(
-- same as [dbo].[VW_MetEd_Master_Profitable_ExcludeBadAddress]
SELECT
IIF (DET.IncalculableMailAddress = 1,
IIF (AA.Address1 IS NULL, 'Bad Address Undefined Fix -- Source Address Provided', 'Fixed Bad Source Address Via Lookup'), '') AS AddressStatus,
DET.ACCT_NO,
(CAST(DET.Monthly1 as Decimal) +
CAST(DET.Monthly2 as Decimal) +
CAST(DET.Monthly3 as Decimal) +
CAST(DET.Monthly4 as Decimal) +
CAST(DET.Monthly5 as Decimal) +
CAST(DET.Monthly6 as Decimal) +
CAST(DET.Monthly7 as Decimal) +
CAST(DET.Monthly8 as Decimal) +
CAST(DET.Monthly9 as Decimal) +
CAST(DET.Monthly10 as Decimal) +
CAST(DET.Monthly11 as Decimal) +
CAST(DET.Monthly12 as Decimal)) AS BilledKWHTotal,
DET.Polar, DET.CustomerName1,
REPLACE (IIF (DET.IncalculableMailAddress = 1,
IIF (AA.Address1 IS NULL, DET.Mailing_Address, AA.Address1), DET.Mailing_Address), ',', ';') AS Address1,
REPLACE (IIF (DET.IncalculableMailAddress = 1,
IIF (AA.Address2 IS NULL, DET.Mailing_Address2, AA.Address2), DET.Mailing_Address2), ',', ';') AS Address2,
REPLACE (IIF (DET.IncalculableMailAddress = 1,
IIF (AA.City IS NULL, DET.Mailing_City, AA.City), DET.Mailing_City), ',', ';') AS City,
IIF (DET.IncalculableMailAddress = 1,
IIF (AA.[State] IS NULL, DET.Mailing_State, AA.[State]), DET.Mailing_State) AS [State],
IIF (DET.IncalculableMailAddress = 1,
IIF (AA.Zip IS NULL, DET.Mailing_Zip, AA.Zip), DET.Mailing_Zip) AS ZIP,
IIF (DET.IncalculableMailAddress = 1, '', DET.Mailing_Zip4) AS ZIP4,
REPLACE (DET.Address, ',', ';') AS ServiceAddress,
REPLACE (DET.City, ',', ';') AS ServiceAddressCity,
DET.State ASs ServiceAddressState,
DET.Zip AS ServiceAddressZip,
DET.Zip4 AS ServiceAddressZip4,
DET.ProfitAnnualPotential AS [Potential Annual Profit]
FROM
_MetEd_DETAIL DET
LEFT JOIN
AccountAddress AA ON (DET.ACCT_NO = AA.ACCT_NO AND AA.UtilityId = 9)
WHERE
RunId = (SELECT RunId FROM LastLoadRuns WHERE UtilityId = 9)
AND DET.Profitable = 1 --AND det.CAP_CUSTOMER = 0
AND (DET.IncalculableMailAddress = 0 OR (AA.Address1 IS NOT NULL))
)
SELECT X.*
FROM MetEdFliers Fliers
OUTER APPLY
(SELECT TOP 1 *
FROM MetEdLookUpFirst LU
WHERE LU.CustomerName1 = Fliers.CustomerName1
AND LU.Address1 = Fliers.Mailing_Address
AND LU.Address2 = Fliers.Mailing_Address2
AND LU.Zip = Fliers.Mailing_Zip) X
It looks to be difficult.
I am going to handle it in my source program that generates input files for the sql server database ( i real the cvs into a table using import ).
To handle this problem, I am going to use a technology called dictionary, with key value pair, in c#.
I will be able to tell if the key had been added before, and if so, I replace the key value pair with the new key value pair and the annual profit potential field with the sum from both records....
Note: Prior method, I did not have sum (enhancement).

DB2 SQL function returning multiple values when I am expecting only one

I am trying to get the location of the last time an item was moved via sql function with the code below. Pretty basic, I'm just trying to grab the max date and time. If I run the sql as a regular select and hard code an item number in ATPRIM I get only one location. But if I create this function and then try to run it and then pass the function an item number I get every occurrence in the history file instead of just the MAX which would be the most recent. Also I have tried a Select Distinct and that did not do anything for me.
ATOGST = Item Location
ATPRIM = Item
ATDATE = Date
ATTIME = Time
CREATE FUNCTION ERPLXU/F#QAT1(AATPRIM VARCHAR(10))
RETURNS CHAR(50)
LANGUAGE SQL
NOT DETERMINISTIC
BEGIN DECLARE F#QAT1 CHAR(50) ;
SET F#QAT1 = ' ' ;
SELECT ATOGST
INTO F#QAT1 FROM ERPLXF/QAT as t1
WHERE ATPRIM = AATPRIM
AND ATDATE = (SELECT MAX(ATDATE) FROM ERPLXF/QAT AS T2
WHERE T2.ATPRIM = AATPRIM)
AND ATTIME = (SELECT MAX(ATTIME) FROM ERPLXF/QAT AS T3
WHERE T3.ATPRIM = AATPRIM
AND T3.ATDATE = T1.ATDATE) ;
RETURN F#QAT1 ;
END
EDIT:
So what I am trying to do is get that location and I got it to work on my iSeries in strsql but the problem is we use a web application called Web Object Wizard (WoW) which lets us use sql to make reports that are more user friendly. Below is what I was trying to get to work but the subquery in the select does not work in WoW so that is where I was trying create a function which we know works in other applications.
SELECT distinct t1.atprim, atdesc, dbtabl, dbdtin, dblife, dblpdp,
dbcost, dbbas, dbresv, dbyrdp, dbcurr,
(select atogst
from erplxf.qat as t2
where t1.atprim = t2.atprim and atdate = (select max(atdate) from
erplxf.qat as t3 where t2.atprim = t3.atprim) and attime = (select
max(attime) from erplxf.qat as t4 where t1.atprim = t4.atprim and
t1.atdate = t4.atdate)
) as #113_ToLoc
FROM erplxf.qat as t1 join erplxf.qdb on atassn = dbassn
where dbrcid = 'DB'
and dbcurr != 0
So instead of that subquery at the end of the select it would just be
, erplxu.f#qat1(atprim) as #113_ToLoc
Try this:
CREATE FUNCTION ERPLXU/F#QAT1(AATPRIM VARCHAR(10))
RETURNS CHAR(50)
LANGUAGE SQL
RETURN
SELECT ATOGST
FROM ERPLXF/QAT
WHERE ATPRIM = AATPRIM
ORDER BY ATDATE DESC, ATTIME DESC
FETCH FIRST 1 ROW ONLY;

Need help joining 3rd table to Stored Proc

I have a stored Procedure that works fine joining 2 tables together. I needed to add a new field from a new table that was not included in the original SP. What I am trying to do is sum a field from the new table for each record that is a child record of the Parent table which is in the original SP.
I tested the Sum based on th parent table in a test query and it works fine:
select totaldollars from TTS_EmpTime where emptimedaytotal_id='32878'
so then the next step would be to integrate into the SP. I did so and have set the new portions of the SP to be bold so you can see what was added. IF the bold portions are removed the SP works fine if not I get this error:
*Msg 8120, Level 16, State 1, Procedure TTS_RptTest2, Line 11
Column 'TTS_EmpTimeDayTotal.EmployeeID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause*.
Here is my Stored Proc:
USE [TTSTimeClock]
GO
/****** Object: StoredProcedure [dbo].[TTS_RptTest2] Script Date: 03/04/2011 12:29:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[TTS_RptTest2]
#BureauID nvarchar(36),
#CompanyID nvarchar(36),
#DivisionID nvarchar(10) ,
#punchDate smalldatetime,
#PeriodDays integer,
#EmployeeID nvarchar(20) = null
As
--with DayTotals as(
select
DayTotal.DivisionID,
DayTotal.EmployeeID,
EmpData.EmployeeFirstName AS First,
EmpData.EmployeeLastName AS Last,
EmpData.employeetypeid AS EmpId,
DayTotal.ID as DayTotalID,
-- Format the Date as MM/DD DOW or 2Digit Month & 2Digit Day and the 3Char Day of the week Uppercase
convert(varchar(5),DayTotal.PunchDate,101) + ' ' + upper(left(datename(dw,DayTotal.Punchdate),3))as PunchDate,
-- Format the in and out time as non military time with AM or PM No Dates
substring(convert(varchar(20), DayTotal.FirstDayPunch, 9), 13, 5) + ' ' + substring(convert(varchar(30), DayTotal.FirstDayPunch, 9), 25, 2)as TimeIn,
substring(convert(varchar(20), DayTotal.LastDayPunch, 9), 13, 5) + ' ' + substring(convert(varchar(30), DayTotal.LastDayPunch, 9), 25, 2) as TimeOut,
DayTotal.RegularHours,
DayTotal.NonOvertimeHours,
DayTotal.OvertimeHours,
DayTotal.TotalDayHRS,
DayTotal.PeriodRegular,
DayTotal.PeriodOtherTime,
DayTotal.PeriodOvertime,
DayTotal.PeriodTotal,
**sum(cast(EmpTime.TotalDollars as float)) as TotalDayDollars**
from TTS_EmpTimeDayTotal as DayTotal
INNER JOIN TTS_PayrollEmployees AS EmpData
ON DayTotal.EmployeeID = EmpData.EmployeeID
**inner JOIN TTS_Emptime as EmpTime
ON DayTotal.id = emptime.emptimedaytotal_id**
where
DayTotal.BureauID = #BureauID
AND DayTotal.CompanyID = #CompanyID
AND (DayTotal.DivisionID = #DivisionID)
AND daytotal.periodstart =
-- Period start date
(SELECT DISTINCT PeriodStart
FROM TTS_EmpTimeDayTotal
WHERE(BureauID = #BureauID) AND (CompanyID = #CompanyID) AND ( (DivisionID = #DivisionID))
AND (PunchDate = #punchDate)and periodend = dateadd(d,(#PeriodDays - 1),(periodstart)))
AND daytotal.periodend =
-- Period End Date
(SELECT DISTINCT PeriodEnd
FROM TTS_EmpTimeDayTotal
WHERE(BureauID = #BureauID) AND (CompanyID = #CompanyID) AND ( (DivisionID = #DivisionID))
AND (PunchDate = #punchDate)and periodend = dateadd(d,(#PeriodDays-1),(periodstart)))
-- Optional all employees or just one
AND (( #EmployeeID is Null) or (DayTotal.EmployeeID = #EmployeeID))
order by Empdata.employeetypeid,DayTotal.punchdate
I am not grouping at all so this must be caused by something else?
Any Help will be appreciated
Is this SQL Server? Looks like it. You're using SUM, an aggregate function, which I don't believe you can use without a GROUP BY clause. Did you always have the SUM in there, or did you add it alongside the new table?
If the latter, that may well be your problem.
Update
Based on OP's comment:
Wow that could be a pain would I do
somehing like groupby field1,field2,
and so on? as in a coma delimited
list. Is there another way to include
this one field that would be better?
Yes, in SQL Server you must be explicit with groupings when using an aggregate function. One alternative in your case would be to do the grouping as a subquery, and join on that, i.e.:
FROM TTS_EmpTimeDayTotal AS DayTotal
INNER JOIN TTS_PayrollEmployees AS EmpData ON DayTotal.EmployeeID = EmpData.EmployeeID
INNER JOIN (SELECT EmpTimeDayTotal_id, SUM(CAST(TotalDollars AS FLOAT)) AS TotalDayDollars
FROM TTS_Emptime
GROUP BY EmpTimeDayTotal_id) AS EmpTime ON DayTotal.id = EmpTime.EmpTimeDayTotal_id
And then simply reference EmpTime.TotalDayDollars in the SELECT list, instead of performing the SUM there.