Reputation: 21
I have the following query
select name,trip_id from main order by name
I want to retrieve count of all the records and all the columns in the tables. for ex if i have 200 rows in table i want to have the output as
select name,trip_id,count(*) from main
Is it possible in a single query?
Upvotes: 1
Views: 45
Reputation: 1521
DECLARE
@Main TABLE
(
[name] VARCHAR(50),
trip_id INT
);
INSERT INTO @Main
(
[name],
trip_id
)
VALUES
(
'Jim', 1
),
(
'Ian', 2
),
(
'Susan', 2
);
-- Option 1
SELECT
[name],
trip_id,
COUNT(*) OVER () AS ct
FROM
@Main;
-- Option 2
SELECT
[name],
trip_id,
(
SELECT
COUNT(*)
FROM
@Main
)
ct
FROM
@Main;
-- Option 3
SELECT
[name],
trip_id,
v.ct
FROM
@Main
CROSS APPLY
(
SELECT
COUNT(*) FROM @Main
) v (ct);
-- Option 4
SELECT
t1.[name],
t1.trip_id,
t2.ct
FROM
@Main t1
JOIN
(
SELECT
COUNT(*) ct
FROM
@Main
) t2
ON 1 = 1;
-- Option 5
SELECT
t1.[name],
t1.trip_id,
t2.ct
FROM
@Main t1
CROSS JOIN
(
SELECT
COUNT(*) ct
FROM
@Main
) t2;
Upvotes: 0
Reputation: 38290
Use analytic count
:
select name, trip_id,
count(*) over() as cnt
from main
order by name
;
Upvotes: 1