[英]Selecting Distinct Fields From Joined Rows
我有一個表ANIMAL
和另一個表CALF_PARENT
ANIMAL
表的設計是:
ID PK IDENTITY(1,1),
TagNo varchar(30)
and other columns...
CALF_PARENT
設計是:
ID PK IDENTITY(1,1),
Parent int (FK from Animal),
IsMother varchar(1)
我正在編寫以下查詢以連接兩個表:
SELECT a.[TagNo]
,a.ID
,a2.TagNo
,isnull(cp.Parent,0)
,a3.TagNo
,isnull(cp.Parent,0)
FROM [dbo].[ANIMAL] a
LEFT JOIN [CALF_PARENT] cp
ON a.ID = cp.Calf
LEFT JOIN ANIMAL a2
ON a2.ID = cp.Parent AND cp.IsMother = 'Y' AND a2.ID IS NOT NULL
LEFT JOIN ANIMAL a3
ON a3.ID = cp.Parent AND cp.IsMother = 'N' AND a3.ID IS NOT NULL
它給我的記錄是這樣的:
Tag, CalfID, FatherTagNo, FatherID, MotherTagNo, MotherID
FA-56 21 AB-670 3
FA-56 21 CW-59 7
我希望它返回我這樣的單行:
Tag, CalfID, FatherTagNo, FatherID, MotherTagNo, MotherID
FA-56 21 AB-670 3 CW-59 7
實現它的最簡單方法是什么。
SELECT DISTINCT a.[TagNo] As Tag
,a.ID As CalfID
,MAX(a2.TagNo) As FatherTagNo
,MAX(isnull(cp.Parent,0)) As FatherID
,MAX(a3.TagNo) As MotherTagNo
,MAX(isnull(cp.Parent,0))As MotherID
FROM [dbo].[ANIMAL] a
LEFT JOIN [CALF_PARENT] cp
ON a.ID = cp.Calf
LEFT JOIN ANIMAL a2
ON a2.ID = cp.Parent AND cp.IsMother = 'Y' AND a2.ID IS NOT NULL
LEFT JOIN ANIMAL a3
ON a3.ID = cp.Parent AND cp.IsMother = 'N' AND a3.ID IS NOT NULL
GROUP BY a.[TagNo] ,a.ID
和例子
declare @t table (id varchar(10),cal int,father varchar(10),fatherid int,mother varchar(20),motherid int)
insert into @t(id,cal,father,fatherid,mother,motherid) values ('FA-56',21,'AB-670',3,NULL,NULL)
insert into @t(id,cal ,father,fatherid,mother,motherid) values ('FA-56',21,null,null, 'CW-59',21)
select distinct id As i,cal,MAX(father),MAX(fatherid),MAX(mother),MAX(motherid) from @t
group by id,cal
嘗試這個:
SELECT a.*, cpmd.*, cpfd.*
FROM dbo.ANIMAL a
LEFT JOIN CALF_PARENT cpm ON a.ID = cpm.Calf AND cpm.IsMother = 'Y'
LEFT JOIN ANIMAL cpmd ON cpmd.ID = cpm.Parent
LEFT JOIN CALF_PARENT cpf ON a.ID = cpf.Calf AND cpf.IsMother = 'N'
LEFT JOIN ANIMAL cpfd ON cpfd.ID = cpf.Parent
如果您的calf_parent表由3列組成,那么您的生活將會更加輕松:
Animal_ID (PK), Father_ID, Mother_ID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.