SQL 服务器:查询以从另一个 table 获取 table 数据(计数)作为 VIEW
SQL Server : query to get table data (count) from another table as VIEW
我有 4 个 table,MASTER, TRANS1, TRANS2
和 TRANS3
。我想通过 table MASTER
中的 USERID
从 tables TRANS1-3
中获取计数。
本次演出 table 供参考。
硕士table:
USERID REF
--------------------
1 Alfa
2 Beta
3 Charlie
4 Delta
5 Echo
TRANS1 table
Id USERID
------------
1 1
2 1
3 2
4 3
5 5
TRANS2 table
Id USERID
------------
1 2
2 3
3 4
4 5
我想return到另一个table或这样查看
USERID COUNT_FROM_TRANS1 COUNT_FROM_TRANS2 COUNT_FROM_TRANS3
--------------------------------------------------------------------
1 2 0 1
2 1 1 2
3 1 1 3
4 0 1 4
5 1 5 5
如何使用 SQL Server 2014?
在这种情况下,关联子查询可能是最简单的解决方案:
select m.*,
(select count(*) from trans1 t where t.user_id = m.user_id) as cnt1,
(select count(*) from trans2 t where t.user_id = m.user_id) as cnt2,
(select count(*) from trans3 t where t.user_id = m.user_id) as cnt3
from master m;
每个trans表在user_id
上都有索引,性能应该也很好
更规范的解决方案将使用 left join
和多个 group by
s:
select m.user_id,
coalesce(t1.cnt, 0) as cnt1,
coalesce(t2.cnt, 0) as cnt2,
coalesce(t3.cnt, 0) as cnt3
from master m left join
(select t.user_id, count(*) as cnt
from trans1 t
group by t.user_id
) t1
on t1.user_id = m.user_id left join
(select t.user_id, count(*) as cnt
from trans2 t
group by t.user_id
) t2
on t2.user_id = m.user_id left join
(select t.user_id, count(*) as cnt
from trans3 t
group by t.user_id
) t3
on t3.user_id = m.user_id;
第一个版本更容易编写,在大多数情况下甚至可能有更好的性能。
我有 4 个 table,MASTER, TRANS1, TRANS2
和 TRANS3
。我想通过 table MASTER
中的 USERID
从 tables TRANS1-3
中获取计数。
本次演出 table 供参考。
硕士table:
USERID REF
--------------------
1 Alfa
2 Beta
3 Charlie
4 Delta
5 Echo
TRANS1 table
Id USERID
------------
1 1
2 1
3 2
4 3
5 5
TRANS2 table
Id USERID
------------
1 2
2 3
3 4
4 5
我想return到另一个table或这样查看
USERID COUNT_FROM_TRANS1 COUNT_FROM_TRANS2 COUNT_FROM_TRANS3
--------------------------------------------------------------------
1 2 0 1
2 1 1 2
3 1 1 3
4 0 1 4
5 1 5 5
如何使用 SQL Server 2014?
在这种情况下,关联子查询可能是最简单的解决方案:
select m.*,
(select count(*) from trans1 t where t.user_id = m.user_id) as cnt1,
(select count(*) from trans2 t where t.user_id = m.user_id) as cnt2,
(select count(*) from trans3 t where t.user_id = m.user_id) as cnt3
from master m;
每个trans表在user_id
上都有索引,性能应该也很好
更规范的解决方案将使用 left join
和多个 group by
s:
select m.user_id,
coalesce(t1.cnt, 0) as cnt1,
coalesce(t2.cnt, 0) as cnt2,
coalesce(t3.cnt, 0) as cnt3
from master m left join
(select t.user_id, count(*) as cnt
from trans1 t
group by t.user_id
) t1
on t1.user_id = m.user_id left join
(select t.user_id, count(*) as cnt
from trans2 t
group by t.user_id
) t2
on t2.user_id = m.user_id left join
(select t.user_id, count(*) as cnt
from trans3 t
group by t.user_id
) t3
on t3.user_id = m.user_id;
第一个版本更容易编写,在大多数情况下甚至可能有更好的性能。