我有一个帐户表,每个帐户表都有一个唯一的ID。然后我有一个交易表,每个帐户表都有一个唯一的ID。Transactions表的每一行都有一个帐号ID,以显示它与哪个特定的帐号相关联。因此,transactions表中可以有多个具有相同帐户ID的行,每个行都指向相同的帐户,以指示该帐户具有多个事务。
每个账户可以有任意数量(0-n)的交易。
我很好地将Transactions表连接到Account表,输出为每个事务显示一行(因此某些帐号有多行),或者,如果没有事务,则在事务字段中显示null:
|Account ID|Account Name|Transaction ID|Transaction Name|
---------------------------------------------------------
|acc1 |Account 1 |tran1 |Transaction 1 |
|acc1 |Account 1 |tran2 |Transaction 2 |
|acc1 |Account 1 |tran3 |Transaction 3 |
|acc2 |Account 2 |tran4 |Transaction 4 |
|acc3 |Account 3 |null |null |
|acc4 |Account 4 |tran5 |Transaction 5 |
|acc4 |Account 4 |tran6 |Transaction 6 |但我想要的是获得事务数量的计数-我不关心与每个事务相关的任何信息;我只想获得每个帐户的事务数量的计数:
|Account ID|Account Name|Number of Transactions|
------------------------------------------------
|acc1 |Account 1 | 3 |
|acc2 |Account 2 | 1 |
|acc3 |Account 3 | 0 |
|acc4 |Account 4 | 2 |我怎样才能得到这个计数呢?
FWIW - Microsoft SQL Server
发布于 2018-08-30 05:31:03
DECLARE @Account TABLE(AccountID INT, AccountName NVARCHAR(50))
DECLARE @Transaction TABLE(AccountID INT, TransactionID INT)
INSERT INTO @Account
VALUES(1,'Acount 1'),
(2,'Acount 2'),
(3,'Acount 3')
INSERT INTO @Transaction
VALUES(1, 1),
(1, 2),
(1, 3),
(2, 4),
(2, 5)
SELECT a.AccountID, a.AccountName, Count(t.TransactionID) AS 'Number Of Transactions' FROM @Account a
LEFT JOIN @Transaction t ON a.AccountID = t.AccountID
Group By a.AccountID, a.AccountName发布于 2018-08-30 04:49:39
假设您的表结构如下
create table tran (accid varchar, accname varchar, tranid varchar, tranname varchar)您只需使用group by子句即可实现此目的
select accid,accname, count(tranid) from tran group by accidhttps://stackoverflow.com/questions/52085677
复制相似问题