表格account
的屏幕截图:
[]
表格trandetails
的屏幕截图:
[
问题:编写查询以显示注册为C00001的客户提取的总数和存款总数。为计数指定Trans_Count的别名。
我想减少上述问题的代码行
我写了这个查询
代码:
with t as
(
select acnumber,transaction_type,count(transaction_type) as trans_type
from trandetails as t
group by transaction_type,acnumber
)
,c as
(
select c.custid,c.acnumber
from account as c
where custid like 'C00001'
)
select c.custid,t.transaction_type,t.trans_type
from t inner join c on c.acnumber = t.acnumber
答案 0 :(得分:1)
SELECT c.custid,
t.transaction_type,
t.trans_type
FROM account AS c
INNER JOIN(
SELECT acnumber,
transaction_type,
COUNT(transaction_type) AS trans_type
FROM trandetails
GROUP BY transaction_type,
acnumber ) t ON c.acnumber = t.acnumber
WHERE c.custid LIKE 'C00001';
如果帐号中的acnumber是唯一的,那么它会更简单:
SELECT c.custid,
t.transaction_type,
COUNT(t.transaction_type) AS trans_type
FROM account AS c
INNER JOIN trandetails AS t ON c.acnumber = t.acnumber
WHERE c.custid LIKE 'C00001'
GROUP BY c.custid,
t.transaction_type;
答案 1 :(得分:0)
尝试此查询
create table tabb (col1 varchar2(20), col2 varchar2(20), test number);
begin
insert into tabb values ('Bala', 'bala',1);
insert into tabb values ('bala', 'Bala',2);
insert into tabb values ('Baba', 'baba',3);
insert into tabb values ('bala', 'Bala',4);
insert into tabb values ('Kumar', 'kumar',5);
end;
select * from tabb where col1 like lower('b%') or col1 like upper('b%') and col2 like lower('b%') or col2 like upper('b%');
答案 2 :(得分:0)
您始终可以使用CTE的子查询
select c.custid,
t.transaction_type,
t.trans_type
from account c
inner join (
select s.acnumber,
s.transaction_type,
count(s.transaction_type) as trans_type
from trandetails as s
group by s.transaction_type,
s.acnumber) t on c.acnumber = t.acnumber
where c.custid = 'C00001'
可能您必须使用s.custid = 'C00001'
或s.custid like '%C00001%'
之类的内容。 like
用于搜索某些字符串的内部,而不是直接比较相等。
答案 3 :(得分:0)
看看这是不是你想要的:
select a.custid
,t.transaction_type
,sum(t.transaction_amount) amount
from account a
,trandetails t
where t.acnumber = a.acnumber
and a.custid = 'C00001'
group by a.custid
,t.transaction_type;
答案 4 :(得分:0)
以下是条件聚合的示例:
copy_to
答案 5 :(得分:0)
提示1:尽可能避免使用子查询
提示2:如果不需要,请不要使用LIKE子句 - 在您的情况下似乎' ='将完成这项工作 - 这是一个小测试样本:
DECLARE @account TABLE (
custid VARCHAR(20),
acnumber VARCHAR(20)
)
DECLARE @trandetails TABLE (
acnumber VARCHAR(20),
transaction_type VARCHAR(20)
)
INSERT INTO
@account
VALUES
('C00001', 'A00001'),
('C00002', 'A00002')
INSERT INTO
@trandetails
VALUES
('A00001', 'Withdrawal'),
('A00001', 'Deposit'),
('A00002', 'Deposit')
SELECT
acc.custid,
td.transaction_type,
count(td.transaction_type) AS trans_cnt
FROM
@account acc
INNER JOIN @trandetails td
ON acc.acnumber = td.acnumber
WHERE
acc.custid = 'C00001'
GROUP BY
acc.custid,
td.acnumber,
td.transaction_type