2

我有不同的表 4 其中是站点、工作、注释和 PO。站点是位置,一个站点可以有多个工作,工作可以有多个注释和 PO,现在我喜欢根据站点编号选择所有工作,并在单个查询中使用注释和 PO 的计数如何使用单个查询来做到这一点. 我使用了这个查询,但这仅显示 PO 计数。使用 SQL-Server 数据库

SELECT jobid, job_title, po_id, count(po.po_id) PO_count, count(notes) note_count
FROM notes
LEFT JOIN job ON jobid = notes_job_id
LEFT JOIN po ON po_job_id = job_id
LEFT JOIN site_detail ON site_id = _job_si_id
LEFT JOIN site_list ON sitelist_id  = site_sitelist_id
WHERE site_id = 116291
GROUP BY  jobid, job_title, po_id

请帮助,在此先感谢,

4

3 回答 3

3

像这样的东西:

select jobid, job_title, 
    (select count(po.po_id) from po where po.po_job_id=jobid) as PO_count,
    (select count(note.id) from notes where notes.notes_job_id=jobid) as note_count,
from job
where site_id = 116291

您应该能够使用任意数量的“子选择作为列”模式来获取不同的计数。另一个好处是它不需要重组您的实际主查询。

列名和连接结构不准确。您必须填补空白。

我发现您的数据库和命名约定不清楚而且很差。为什么不使用表名/别名作为限定词?这意味着您可以在不同的表中将外键列命名为相同,因此连接将非常清晰和明显,而不是这种丑陋的前缀它们。

我会非常简单地设计它:

notes.FK_JOB      -> job.ID
po.FK_JOB         -> job.ID
site_jobs.FK_SITE -> site.ID
site_jobs.FK_JOB  -> job.ID

这不是简单得多吗?

我也不知道 PO 是什么,除了它既容易发生冲突(与别名、其他列、临时名称)并且信息量不足。两者都是因为它非常短。

于 2013-09-24T09:46:36.020 回答
0

一种方法是count(distinct ...)在表的主键上使用:

SELECT  jobid
,       job_title
,       count(distinct po.po_id) po_count
,       count(distinct site.site_id) site_count
,       count(distinct note.note_id) note_count
,       ...
于 2013-09-24T09:44:50.023 回答
0

我会在加入之前汇总计数,我认为这是最有效的方法:

select
    j.jobid, j.job_title, po.po_count,
    ...
from job as j
    left outer join (
        select count(*) as po_count, po.po_job_id
        from po as po
        group by po.po_job_id
    ) as po on po.po_job_id = j.job_id
    ...
where j.site_id = 116291

顺便说一句,当你不使用<table name>.<column name>符号时,真的很难阅读查询,我强烈建议对表使用别名,对所有列使用点符号

于 2013-09-24T10:06:06.090 回答