如何统计子行?

时间:2013-10-17 08:08:33

标签: sql sqlite

我的sqlite数据库中有两个表 - 招标和批量。

标段:

id
name
address

批次:

id
tender_id # it's tender's ID from table `tenders`
summ

一次招标可能有很多。如何计算有0手的投标?

我尝试了以下查询:

select lots.* from lots
inner join tenders on tenders.id = lots.tender_id
group by lots.id
having count(*) =0

SELECT COUNT(tenders.id) AS cnt FROM tenders, lots WHERE lots.tender_id = tenders.id group by tenders.id having cnt=0

没有结果。 但是当我尝试做的时候

select * from lots where tender_id=263128

结果我看到0行。

谢谢。

4 个答案:

答案 0 :(得分:0)

SELECT tenders.id 
FROM tenders 
WHERE tenders.id NOT IN (SELECT tender_id FROM lots)

或不同数量的批次:

SELECT tenders.id
FROM tenders
WHERE tenders.id IN 
(
SELECT tender_id FROM lots GROUP BY tender_id HAVING COUNT(*) IN (2,3)
)

答案 1 :(得分:0)

你的加入尝试看起来很有希望,但当然你没有得到任何结果,因为你选择了很多。

我会反过来做它left join,这样你可以检查批量null

select
        tenders.id
    from tenders
    left join lots on tenders.id = lots.tender_id
    where lots.tender_id is null

或者,如果您想检查每次招标的具体抽签次数:

select
        tenders.id
    from tenders
    left join lots on tenders.id = lots.tender_id
    group by tenders.id
    having count(*) = 2

答案 2 :(得分:0)

使用子查询:

SELECT id, (SELECT COUNT() FROM lots WHERE tender_id=tenders.id) AS LotCount FROM tenders;

答案 3 :(得分:0)

<强>嗨, 这会对你有所帮助......

SELECT * FROM (
SELECT T.*, (SELECT COUNT(*) FROM lots L WHERE L.empid = T.empid) AS 'RecordFound'  
FROM tenders AS T) TendersLots
WHERE RecordFound = 0

谢谢, Vishal Patel