我有以下查询
select name,trip_id from main order by name
我想检索表中所有记录和所有列的计数。 例如,如果我在表中有200行,我希望输出为
select name,trip_id,count(*) from main
在单个查询中有可能吗?
答案 0 :(得分:1)
使用解析count
:
select name, trip_id,
count(*) over() as cnt
from main
order by name
;
答案 1 :(得分:0)
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;