Nic*_*ahn 8 sql sql-server-2008
ReporterTbl与...有一对多的关系AttachmentTbl.
在ReporterTbl,我有一个ID(101),我可以有AttachmentTbl多个Attachment与之相关的ReporterTbl.Id
SELECT
ISNULL(ReporterTbl.Id, 0) AS Id,
CONVERT(char(10), ReporterTbl.StartDate, 101) AS StartDate,
ISNULL(ReporterTbl.PriorityId, 0) AS PriorityId,
ISNULL(dbo.ReporterTbl.PriorityDesc, '') AS PriorityDesc,
(select
ReporterTbl.Id,
COUNT(dbo.AttachmentTbl.Id) AS attachment_Id
FROM
dbo.AttachmentTbl RIGHT OUTER JOIN
ReporterTbl ON dbo.AttachmentTbl.Id = ReporterTbl.Id
GROUP BY ReporterTbl.Id) AS IsAttachment
)
Run Code Online (Sandbox Code Playgroud)
基本上,我想知道的是ReporterTbl.ID,Attachment我有多少?
表结构:
ReporterTbl
Id int {**PrimaryKey**}
StartDate datetime
PriorityId int
PriorityDesc varchar(500
AttachmentTbl:
AttachmentId indentity
Id {**FK to ReproterTbl**}
Filename
Content
...
Run Code Online (Sandbox Code Playgroud)
Red*_*ter 22
select r.id, count(a.id) as Count
from ReporterTbl r
left outer join AttachmentTbl a on r.id = a.id
group by r.id
Run Code Online (Sandbox Code Playgroud)
如果你想从报告中获取所有字段(不仅仅是ID),这将为您节省JOIN:
SELECT r.*,
(
SELECT COUNT(*)
FROM AttachmentTbl a
WHERE a.id = r.id
) AS AttachmentCount
FROM ReportedTbl r
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13432 次 |
| 最近记录: |