您好我是数据库的新手。我需要通过查询使用case语句和数据库中的结果的最大值来显示数组。
下面是我使用的mysql db的表数据。
create table department (deptid int not null auto_increment,deptname varchar(20) not null,primary key ( deptid));
DEPARTMENT表数据:
deptid | deptname
-------+---------
1 | IT
2 | HR
3 | ADMIN
客户表创建脚本。
create table customer (
custid int not null auto_increment,
custname varchar(20) not null,
recordkey int,
deptid int,
primary key (custid),
foreign key (deptid) references Department(deptid)
);
客户表数据:
custid | custname | recordkey | deptid
-------+----------+-----------+-------
1 | A | 1 | 1
2 | B | 1 | 2
3 | C | 1 | 1
-------+----------+-----------+--------
下面我尝试使用group by
查询结果。
select c.recordkey,count(d.deptid),d.deptname from department d join
customer c on d.deptid=c.deptid
group by c.recordkey,d.deptid,d.deptname;
结果:
recordkey | count(d.deptid) | deptname
----------+-----------------+---------
1 | 2 | IT
1 | 1 | HR
我也尝试过案例陈述:
select c.recordkey,d.deptname,
case when d.deptname='IT' then count(d.dept name)
else 0 end as itcount,
case when d.deptname='HR' then count(d.deptname)
else 0 end as hrcount from department d
join customer c on d.deptid=c.deptid
group by c.recordkey,d.deptname;
结果:
recordkey | deptname | itcount | hrcount
----------+----------+---------+--------
1 | HR | 0 | 1
1 | IT | 2 | 0
根据要求,结果必须是单行。
但最终结果应为deptid
,其中count
和max
来自计数。例如,IT部门有最大记录。
recordkey | itdeptid | itdeptname | itocunt | hrdeptid | hrdeptname | hrcount | admindeptid | admindeptname | admincount | max of (itocunt hrcount admincount)
----------+----------+------------+---------+----------+------------+---------+-------------+---------------+------------+------------------------------------
1 | 1 | IT | 2 | 2 | HR | 1 | 3 | ADMIN | 0 | 2
如果有人有任何建议,那就太好了。