简化我的数据库样本是一个表格,如
CN REG# CAPACITY
---------- ---------- ----------
0 LUCY02 43000
6 QRT834 5550
3 SYF777 3333
12 PKR768 1234
5 SST005 12000
6 KKK007 10000
3 PKR008 22000
这是通过连接两个表创建的。这是连接声明:
select count(tp.reg#) as cn,t.reg#, CAPACITY
from truck t
join trip tp
on t.reg# = tp.reg#
group by tp.reg#, CAPACITY, t.reg#
现在,我如何编写一个语句来仅打印具有最小出现次数和非零次数的行。在我们的例子中它是3。
预期输出
3 SYF777 3333
3 PKR008 22000
到目前为止,我所做的却不起作用:
select count(tp.reg#) as cn,t.reg#, CAPACITY
from truck t
left join trip tp
on t.reg# = tp.reg#
left join
(
select dd, min(d) as ds
from(
select count(*)as d, ti.CAPACITY, ti.reg# as dd
from truck ti, trip tp
where tp.reg# = ti.reg#
group by ti.reg#, ti.CAPACITY
)
group by dd
)
on t.reg# = dd
group by tp.reg#, CAPACITY, t.reg#
答案 0 :(得分:4)
如果您想根据" count"这样的聚合函数过滤您的查询,只需在"中添加"语句:
select count(tp.reg#) as cn,t.reg#, CAPACITY
from truck t
join trip tp
on t.reg# = tp.reg#
group by tp.reg#, CAPACITY, t.reg#
having count(tp.reg#) >= 3
如果您想要动态最小的查询记录,可以使用以下代码:
select count(tp.reg#) as cn,t.reg#, CAPACITY
from truck t
join trip tp
on t.reg# = tp.reg#
group by tp.reg#, CAPACITY, t.reg#
having count(tp.reg#) = (select distinct top 1 count(tp.reg#) cn
from truck t
join trip tp
on t.reg# = tp.reg#
group by tp.reg#, CAPACITY, t.reg#
having count(tp.reg#) >0
order by cn)
答案 1 :(得分:1)
嗨,你可以试试这个,
select * from
(select count(tp.reg#) as cn,t.reg#, CAPACITY
from truck t
join trip tp
on t.reg# = tp.reg#
group by tp.reg#, CAPACITY, t.reg#)
where cn = (select min(cn) from (select count(tp.reg#) as cn,t.reg#, CAPACITY
from truck t
join trip tp
on t.reg# = tp.reg#
where cn > 0
group by tp.reg#, CAPACITY, t.reg#))
我希望对你有用... 感谢
答案 2 :(得分:0)
您只需要对动态视图进行几次转换,并在中途添加过滤:
select min(y.cn) , y.REG#, y.CAPACITY
from
(
select x.CN, x.REG#, x.CAPACITY
FROM
(
select count(tp.reg#) as cn,t.reg#, CAPACITY
from truck t
join trip tp
on t.reg# = tp.reg#
group by tp.reg#, CAPACITY, t.reg#
) X
WHERE x.cn != 0
) y
group by y.REG#, y.CAPACITY