November 17, 2009 at 1:25 am
Dear All,
I have a problem to calculate all record and calculate one field which have two data different.
Example:
ID Status
------------
123 Active
234 Active
345 Inactive
567 Inactive
678 Inactive
how to display count record and calculating from field status?
Result:
Active Inactive Total
2 3 5
Thanks,
November 17, 2009 at 1:37 am
SELECT
SUM(CASE Status WHEN 'Active' THEN 1 ELSE 0 END) AS SumActive,
SUM(CASE Status WHEN 'Inactive' THEN 1 ELSE 0 END) AS SumInactive
Count(*) AS Total
FROM SomeTable
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
November 17, 2009 at 1:38 am
ROLLUP is what you're looking for:
DECLARE @TempTab TABLE (
[ID] int,
[Status] varchar(10)
)
INSERT INTO @TempTab VALUES (123, 'Active')
INSERT INTO @TempTab VALUES (234, 'Active')
INSERT INTO @TempTab VALUES (345, 'Inactive')
INSERT INTO @TempTab VALUES (567, 'Inactive')
INSERT INTO @TempTab VALUES (678, 'Inactive')
SELECT [Status], COUNT(*)
FROM @TempTab
GROUP BY [Status]
WITH ROLLUP
If you were using SQL2008 you could use the new syntax ROLLUP([Status]).
Regards
Gianluca
-- Gianluca Sartori
November 17, 2009 at 1:46 am
Now that I see Gail's reply I understand that you need it in one single row.
Another way to achieve it is with PIVOT:
SELECT [Active], [Inactive], [Total] = [Active] + [Inactive]
FROM @TempTab
PIVOT (COUNT(ID) FOR [Status] IN ([Active],[Inactive])) AS PVT
-- Gianluca Sartori
November 17, 2009 at 2:03 am
Thanks Gianluca,
Thanks Gail Shaw
I get the simple solution from you.
Regads,
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply