我有两张桌子:
MED
create table t1(id int,cust int, [order] int)
go
create table t2(id int,cust int,parts1 int,parts2 int)
go
insert t1 values(1,1,1)
insert t1 values(2,1,1)
insert t1 values(3,1,1)
insert t1 values(4,2,1)
go
insert into t2 values(1,1,5,3)
go
select * from t1
select * from t2
select a.cust ,a.orders,isnull(b.parts1,0) +isnull(b.parts2,0) from
(select cust ,SUM([order] ) as orders from t1 group by cust ) a
left join t2 b on a.cust =b.cust
即
CREATE TABLE med
(id_med INT AUTO_INCREMENT PRIMARY KEY,
name_m VARCHAR(50),
surname_m VARCHAR(50),
spec VARCHAR(50),
UNIQUE (surname_m,name_m));
我需要为每个规范选择fullname和count(id_p)的前3个值。 以下查询给出了第一个值,但我不知道下一步该做什么。
CREATE TABLE viz
(id_m INT NOT NULL,
id_p INT NOT NULL,
id_c INT NOT NULL,
dt DATETIME)
任何答案都将受到高度赞赏。谢谢。
结果应该是这样的:
(SELECT distinct(concat(name_m,' ',surname_m)) AS fullname, COUNT(id_p) as no, (select distinct(spec))
FROM med m JOIN viz v ON m.id_med = v.id_m
WHERE year(dt)=2005
GROUP BY spec
ORDER BY spec;
...
我目前的结果显示:
fullname count(id_p) spec
name1 1000 a
name2 900 a
name3 890 a
name4 2000 b
name5 600 b
name6 200 b
name7 100 c
name8 60 c
name9 59 c
答案 0 :(得分:0)
加入一个子查询,该子查询返回spec
列的前三个值。
SELECT DISTINCT CONCAT(name_m, ' ', 'surname_m) AS fullname, COUNT(id_p) AS no, m1.spec
FROM med AS m1
JOIN viz AS v ON m1.id_med = v.id_m
JOIN (SELECT DISTINCT spec
FROM med
ORDER BY spec
LIMIT 3) AS m2 ON m1.spec = m2.spec
WHERE YEAR(v1.dt) = 2005
GROUP BY fullname, m1.spec
ORDER BY fullname, m1.spec