如何在单个查询中检索所有记录和其他记录的计数

时间:2019-02-23 17:41:45

标签: hive hiveql

我有以下查询

 select name,trip_id from main order by name

我想检索表中所有记录和所有列的计数。 例如,如果我在表中有200行,我希望输出为

select name,trip_id,count(*) from main

在单个查询中有可能吗?

2 个答案:

答案 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;