精炼SQL查询

时间:2011-06-30 16:48:26

标签: sql

我的查询返回的数据过多。这是查询,一些示例数据和我真正喜欢的样本。

select sd.ident,sd.suniq, td.testc, td.testuniq, td.subtestc, ts.testscore, ud.metadept, max(ts.takendt)AS testdate
from studemo sd, stutests ts, testdef td, udefstu ud
where ts.suniq =sd.suniq
and td.testuniq = ts.testuniq
and ts.suniq = ud.suniq
and td.testuniq IN ('2000089', '2000090', '2000091', '2000092')
group by sd.suniq, sd.ident, td.testc, td.subtestc, ts.testscore, ud.metadept, ts.takendt, td.testuniq
order by suniq

示例输出

ident   suniq   testc   testuniq    subtestc    testscore   metadept    testdate
102201  2001444 ADEPT   2000091 L3  23  NULL    09/01/2006 00:00
102201  2001444 ADEPT   2000092 L4  7   NULL    06/01/2007 00:00
101184  2001532 ADEPT   2000092 L4  5   NULL    09/01/2006 00:00
101184  2001532 ADEPT   2000092 L4  7   NULL    06/01/2006 00:00
101184  2001532 ADEPT   2000092 L4  7   NULL    06/01/2007 00:00
590122  2001950 ADEPT   2000091 L3  22  NULL    06/01/2007 00:00
590122  2001950 ADEPT   2000090 L2  32  NULL    09/01/2006 00:00
141058  2004980 ADEPT   2000089 L1  27  NULL    05/01/2006 00:00
141058  2004980 ADEPT   2000090 L2  28  NULL    01/25/2008 00:00
141058  2004980 ADEPT   2000090 L2  27  NULL    06/01/2007 00:00

通缉输出

102201  2001444 ADEPT   2000092 L4  7   NULL    06/01/2007 00:00
101184  2001532 ADEPT   2000092 L4  7   NULL    06/01/2007 00:00
590122  2001950 ADEPT   2000091 L3  22  NULL    06/01/2007 00:00
141058  2004980 ADEPT   2000090 L2  28  NULL    01/25/2008 00:00

2 个答案:

答案 0 :(得分:0)

试试这个。您有太多GROUP BY条件,并且需要在其余字段上进行聚合。从您想要的输出中,它们看起来都像MAX值:

select  sd.ident,
        sd.suniq, 
        td.testc, 
        MAX(td.testuniq) as TestUniq, 
        MAX(td.subtestc) as Subtestc, 
        MAX(ts.testscore) as TestScore, 
        MAX(ud.metadept) as metadept, 
        max(ts.takendt)AS testdate
from studemo sd, stutests ts, testdef td, udefstu ud
where ts.suniq =sd.suniq
and td.testuniq = ts.testuniq
and ts.suniq = ud.suniq
and td.testuniq IN ('2000089', '2000090', '2000091', '2000092')
group by sd.suniq, sd.ident, td.testc,
order by suniq

答案 1 :(得分:0)

我想我知道你的目标是什么,你试图让最新(或最高价值)的项目独家显示...你试过'distinct'关键字吗?如果我有一个测试数据集来尝试一些查询,我可以很快得到你正确的答案,但从头脑中拉出它是另一个故事

选择不同的sd.ident,sd.suniq,td.testc,td.testuniq,td.subtestc,ts.testscore,ud.metadept,max(ts.takendt)AS testdate 来自studemo sd,stutests ts,testdef td,udefstu ud 其中ts.suniq = sd.suniq 和td.testuniq = ts.testuniq 和ts.suniq = ud.suniq 和td.testuniq IN('2000089','2000090','2000091','2000092') group by sd.suniq,sd.ident,td.testc,td.subtestc,ts.testscore,ud.metadept,ts.takendt,td.testuniq 订购suniq desc