【发布时间】:2022-12-16 13:27:15
【问题描述】:
我正在尝试构建一个查询,该查询获取每个用户不同类型的复制的总和。我想显示一个统一的结果,其中包含每个复制的行和将它们汇总为每个用户的所有行的另一行。这是查询:
SELECT replica_name,
user_id,
short_name,
number_of_replications,
firstReplication,
lastReplication
FROM (SELECT 'Initial' AS replica_name,
sc.user_id AS user_id,
u.short_name AS short_name,
Count(sc.user_id) AS number_of_replications,
Min(sc.connected_at) AS firstReplication,
Max(sc.connected_at) AS lastReplication
FROM phoenix.synchro_connections sc
JOIN phoenix.users u
ON u.user_id = sc.user_id
WHERE Lower(sc.synchro_type) = 'initial'
AND sc.size_in_bytes IS NOT NULL
GROUP BY sc.user_id,
u.short_name,
sc.synchro_type
UNION ALL
SELECT 'Delta' AS replica_name,
sc.user_id AS user_id,
u.short_name AS short_name,
Count(sc.user_id) AS number_of_replications,
Min(sc.connected_at) AS firstReplication,
Max(sc.connected_at) AS lastReplication
FROM phoenix.synchro_connections sc
JOIN phoenix.users u
ON u.user_id = sc.user_id
WHERE Lower(sc.synchro_type) = 'delta'
AND sc.size_in_bytes IS NOT NULL
GROUP BY sc.user_id,
u.short_name,
sc.synchro_type
UNION ALL
SELECT 'All' AS replica_name,
sc.user_id AS user_id,
u.short_name AS short_name,
Count(sc.user_id) AS number_of_replications,
Min(sc.connected_at) AS firstReplication,
Max(sc.connected_at) AS lastReplication
FROM phoenix.synchro_connections sc
JOIN phoenix.users u
ON u.user_id = sc.user_id
WHERE Lower(sc.synchro_type) <> 'upload'
AND sc.size_in_bytes IS NOT NULL
GROUP BY sc.user_id,
u.short_name,
sc.synchro_type) AS t
WHERE short_name = 'BY060955'
ORDER BY replica_name ASC,
number_of_replications DESC
这是结果:
replica_name user_id short_name number_of_replications firstReplication LastReplication
All 22472 BY060955 836 2022-11-14 06:26:05.2415463 2022-12-08 10:25:17.4282712
All 22472 BY060955 2 2022-11-14 06:25:08.2385837 2022-11-16 11:55:41.0263526
Delta 22472 BY060955 836 2022-11-14 06:26:05.2415463 2022-12-08 10:25:17.4282712
Initial 22472 BY060955 2 2022-11-14 06:25:08.2385837 2022-11-16 11:55:41.0263526
我希望“全部”成为单行 (836+2 = 838),但“增量”和“初始”保持原样
【问题讨论】:
标签: sql sql-server