[英]Design a database and write a SQL query for score application
假設您想要最終分數的分數總和,您可以使用join
s。 這是一種方法:
select d.*,
(coalesce(mh.score, 0) + coalesce(ms.score, 0) + coalesce(md.score, 0)) as total_score
from data d left join
master mh
on mh.field = 'Hardware Strength' and
mh.option = d.hardware_strength left join
master ms
on msfield = 'Sofware Security' and
ms.option = d.software_security left join
master md
on mh.field = 'Device OS' and
mh.option = d.device_os;
如果你稍微整理一下你的數據庫,你可以直接做到這一點:
create table phones (
id SERIAL PRIMARY KEY,
model varchar(20) NOT NULL UNIQUE,
hardware_strength INT NOT NULL,
software_security INT NOT NULL,
os INT NOT NULL
);
create table hardware_strength (
id SERIAL PRIMARY KEY,
description varchar(20) NOT NULL UNIQUE,
score INT NOT NULL
);
create table software_security (
id SERIAL PRIMARY KEY,
description varchar(20) NOT NULL UNIQUE,
score INT NOT NULL
);
create table os (
id SERIAL PRIMARY KEY,
description varchar(20) NOT NULL UNIQUE,
score INT NOT NULL
);
有了這個 model,查詢很簡單:
SELECT
a.*,
b.score + c.score + d.score as score
FROM phones a, hardware_strength b, software_security c, os d
WHERE
a.hardware_strength = b.id AND
a.software_security = c.id AND
a.os = d.id
;
您可以在這個sqlfiddle中使用它。
設置具有任意數量標准的結構的傳統方法如下所示:
create table phones (pid int identity primary key, pnam varchar(64));
insert into phones (pnam) values ('Google X'),('Samsung P');
create table props (id int, crit varchar(32),
val varchar(32));
create table scores (critsc varchar(32), valsc varchar(32), score int);
insert into props values (1,'hw','metal'),(1,'sec','high'),(1,'os','android'), (2,'hw','diamond'),(2,'sec','low'),(2,'os','windows');
insert into scores values ('hw','plastic',3),('hw','glas',5),('hw','metal',8),('hw','diamond',10),('sec','low',2),('sec','high',5),('os','windows',4),('os','java',6),('os','meego',7),('os','android',10);
select coalesce(pnam,'ALL MODELS') pnam,
coalesce(crit,'total score') crit,
case when crit>'' then max(val) else '' end val, sum(score) score
from phones
inner join props on pid=id
inner join scores on critsc=crit and valsc=val
group by pnam,crit with rollup
Output:
pnam crit val score
Google X hw metal 8
Google X os android 10
Google X sec high 5
Google X total score 23
Samsung P hw diamond 10
Samsung P os windows 4
Samsung P sec low 2
Samsung P total score 16
ALL MODELS total score 39
演示: https://rextester.com/NMKGY74929
誠然,這不是最短的方法,但它允許使用各種標准和值方案,而無需更改表結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.