带分组和计数的SQL查询

时间:2014-12-10 18:56:34

标签: sql ms-access group-by

我有这个ms访问查询:

SELECT weber, t1.artnr, t1.varnr, t1.lfdnr_kal, fert.invnr, fert.min, fert.[lst/h] FROM (
SELECT stammdat.weber, lackzahlen.artnr, lackzahlen.varnr, first(stammdat.[lfdnr-kal]) AS lfdnr_kal
FROM lackzahlen LEFT JOIN stammdat ON (lackzahlen.artnr=cstr(IIf(stammdat.artnr Is Null,'',cstr(stammdat.artnr)))) AND (lackzahlen.varnr=cstr(IIf(stammdat.varnr Is Null,'',cstr(stammdat.varnr)))) 
GROUP BY lackzahlen.artnr, lackzahlen.varnr, io_stkzahl, weber) AS t1
LEFT JOIN fert ON (t1.lfdnr_kal=fert.[lfdnr-kal]) AND (t1.artnr=cstr(iif(fert.artnr Is Null,'',cstr(fert.artnr)))) WHERE fert.invnr IN ('338902', 'R20000')

现在,我想过滤图片上的记录:

enter image description here

如你所见,我想有记录,其中有pro weber,artnr,varnr,lfdnr_kal和invnr多行具有相同的min和lst / h值。

我想,我应该使用cound(也许有数)和分组。但是如何?

在示例中,我没有标记所有行。

2 个答案:

答案 0 :(得分:1)

添加group byhaving以获取重复的行

  GROUP BY weber, t1.artnr, t1.varnr, t1.lfdnr_kal, fert.invnr, fert.min, fert.[lst/h]
  having count(*) >1

答案 1 :(得分:0)

尝试下面的SQL:因为你没有提到总和或AVG值,我猜不同的记录将解决你的问题。



select weber, a.artnr,a.varnr, a.lfdnr_kal, a.invnr, a.min, a.lst_h
(
SELECT weber, t1.artnr, t1.varnr, t1.lfdnr_kal, fert.invnr, fert.min, fert.[lst/h] as lst_h FROM (
SELECT stammdat.weber, lackzahlen.artnr, lackzahlen.varnr, first(stammdat.[lfdnr-kal]) AS lfdnr_kal
FROM lackzahlen LEFT JOIN stammdat ON (lackzahlen.artnr=cstr(IIf(stammdat.artnr Is Null,'',cstr(stammdat.artnr)))) AND (lackzahlen.varnr=cstr(IIf(stammdat.varnr Is Null,'',cstr(stammdat.varnr)))) 
GROUP BY lackzahlen.artnr, lackzahlen.varnr, io_stkzahl, weber) AS t1
LEFT JOIN fert ON (t1.lfdnr_kal=fert.[lfdnr-kal]) AND (t1.artnr=cstr(iif(fert.artnr Is Null,'',cstr(fert.artnr)))) WHERE fert.invnr IN ('338902', 'R20000')
) a group by weber, a.artnr,a.varnr, a.lfdnr_kal, a.invnr, a.min, a.lst_h 
Having count(*) > 1




希望这会有所帮助:)