mysql报告sql帮助

时间:2010-12-24 04:11:35

标签: mysql

我有这样的数据的mysql表。记录将包含具有总cpu的服务器和具有cpu assinged的虚拟服务器

type, cpu
srv1,   10
vsrv11, 2
vsrv12,  3
srv2,   15
vsrv21, 6
vsrv22,  7
vsrv23,  1

从上面的数据中,我想创建这样的输出。

server, total cpu, assigned cpu, free cpu
srv1, 10, 5, 5
srv2, 15, 14, 1

你能帮我创建这个报告的SQL查询吗?


我已经改变了我的表和数据。

CREATE TABLE `cpuallocation` (
  `servertype` varchar(10) DEFAULT NULL,
  `servername` varchar(20) DEFAULT NULL,
  `hostname` varchar(20) DEFAULT NULL,
  `cpu_count` float DEFAULT NULL,
  UNIQUE KEY `server_uniq_idx` (`servertype`,`servername`,`hostname`)

insert into cpuallocation values('srv', 'server1', '',16);
insert into cpuallocation values('vir', 'server1', 'host1',5);
insert into cpuallocation values('vir', 'server1', 'host2',2.5);
insert into cpuallocation values('vir', 'server1', 'host3',4.5);
insert into cpuallocation values('srv', 'server2', '',8);
insert into cpuallocation values('vir', 'server2', 'host1',5);
insert into cpuallocation values('vir', 'server2', 'host2',2.5);
insert into cpuallocation values('srv', 'server3', '',24);
insert into cpuallocation values('vir', 'server3', 'host1',12);
insert into cpuallocation values('vir', 'server3', 'host2',2);
insert into cpuallocation values('srv', 'server4', '',12);

更新

我创建了两个视图,现在我得到了我想要的结果。

create view v1 as 
select servername, sum(cpu_count) as cpu_allocated 
from cpuallocation where servertype='vir' group by servername;

create view v2 as 
select servername, cpu_count as total_cpu 
from cpuallocation where servertype='srv';

select a.servername, a.total_cpu, b.cpu_allocated 
from v2 as a left join v1 as b on a.servername=b.servername;

+------------+-----------+---------------+
| servername | total_cpu | cpu_allocated |
+------------+-----------+---------------+
| server1    |        16 |            12 |
| server2    |         8 |           7.5 |
| server3    |        24 |            14 |
| server4    |        12 |          NULL |
+------------+-----------+---------------+
4 rows in set (0.00 sec)

是否可以创建一个没有创建视图的查询?

2 个答案:

答案 0 :(得分:0)

假设您可以将虚拟服务器映射到真实服务器(例如通过BELONGS_TO功能),您可以将表连接到自身或使​​用如下的子选择:

  

选择r.type作为服务器,r.cpu作为total,sum(从tablename v中选择cpu,其中v.type BELONGS_TO(r.type))作为已分配,total - 从tablename r中分配为free;

对于映射您可以尝试类似

的内容
  

v.name,如CONCAT('%',r.type,'%')

但结果可能不准确:'vsrv111'不明确,可能属于srv11或srv1。

答案 1 :(得分:0)

这应该可用于原始表格格式

select 
  a.type as server,
  a.cpu as total_cpu,
  sum(b.cpu) as assigned_cpu,
  a.cpu-sum(b.cpu) as free_cpu
from cpu as a
left join
  cpu as b on locate(concat('v',a.type), b.type)<>0
where a.type in('srv1', 'srv2')
group by a.type;

您的表似乎没有共同的自然键,您应该指定一个

这对更新的架构非常有用:

select
  cpu1.servername as server,
    cpu1.cpu_count as total_cpu,
    ifnull(sum(cpu2.cpu_count), 0) as assigned_cpu,
    ifnull(cpu1.cpu_count-sum(cpu2.cpu_count),0) as free_cpu
from 
  cpuallocation as cpu1
left join
  cpuallocation as cpu2
  on cpu1.servername=cpu2.servername and cpu2.servertype='vir'
where 
  cpu1.hostname = '' 
group by cpu1.servername;