This topic has been reported for inappropriate content
April 8, 2020 at 9:07 pm
Below is the sample data
create table temp (userid int , rid varchar(10), value varchar(100))
insert into temp(userid,rid,value)
values(1,'D01','3'),
(1,'D01','4'),
(2,'C01','hey'),
(2,'C01','1')
expected output:
1,'D01','7'
2,'C01','hey'
2,'C01','1'
I tried below code and it is throwing error
select distinct userid,rid,
case when ISNUMERIC(value) = 1
THEN
SUM(cast(value as int))
over (partition by userId,rid order by userid)
else value
end as [Value]
from temp
April 8, 2020 at 9:23 pm
To stay on the safe side and since you're on SQL Server 2012, you can use TRY_CAST rather than ISNUMERIC here. ISNUMERIC can do some strange things, as Phil Factor mentions in his article here.
Would you be able to separate these out using a UNION ALL?
SELECT userid, rid, CAST(SUM(CAST([value] AS int)) AS varchar (100)) AS [value]
FROM temp
WHERE TRY_CAST([value] AS int) IS NOT NULL
GROUP BY userid, rid
UNION ALL
SELECT userid, rid, [value]
FROM temp
WHERE TRY_CAST([value] AS int) IS NULL;
This would also avoid your conversion errors.
April 8, 2020 at 9:26 pm
SELECT t.userid
,t.rid
,Total = SUM(TRY_CAST(t.value AS INT))
FROM temp t
GROUP BY t.userid
,t.rid
ORDER BY t.userid;
But why on Earth do you have a numeric column defined as VARCHAR()???
The absence of evidence is not evidence of absence
- Martin Rees
The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
- Phil Parkin
April 9, 2020 at 4:18 am
SELECT t.userid
,t.rid
,Total = SUM(TRY_CAST(t.value AS INT))
FROM temp t
GROUP BY t.userid
,t.rid
ORDER BY t.userid;But why on Earth do you have a numeric column defined as VARCHAR()???
+100,000,000
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply