sql inner join引用子查询中的表

时间:2017-12-05 18:32:39

标签: sql sql-server

以下查询:

select 
    yu.Soyad, 
    mt.ICD10Kodu, 
    count(mi.ID) as AASayisi 
from 
    Muayene.Muayene mm
    join Muayene.Ilac mi 
        on mm.ID = mi.MuayeneId
    join Yetkilendirme.Users yu 
        on mi.CreatedBy = yu.ID
    join Muayene.Tani mt 
        on mm.ID = mt.MuayeneId
where 
    mm.IsDeleted <> 1 
    and mi.IsDeleted <> 1 
    and mt.IsDeleted <> 1  
group by 
    yu.Soyad, 
    mt.ICD10Kodu

返回以下数据:

HALAÇ           J00 5
DEĞİRMENCİOĞLU  J00 12
GÖKALP          J02 22
DİKİLİLER       J03 14

但实际上我需要实体的比率而不是它出现的确切数字,所以我需要将它除以这样:

select 
    yu.Soyad, 
    mt.ICD10Kodu, 
    count(mi.ID)/count(select * from Muayene.Muayene where ID=mm.ID) as AASayisi 
from 
    Muayene.Muayene mm
    join Muayene.Ilac mi 
        on mm.ID = mi.MuayeneId...

但它不起作用。它给出了错误消息:

  

无法找到多部分标识符mi.ID

我怎样才能让它发挥作用?

2 个答案:

答案 0 :(得分:1)

你不能这样做,因为你没有对mm.ID字段进行分组。您应该在分隔查询中计算计数,然后您可以将它们连接起来计算比率;

select yu.Soyad, mt.ICD10Kodu, AASayisi, MMSayisi, (cast(AASayisi as float)/cast(MMSayisi as float)) As Ratio from (
select yu.ID as YUID, yu.Soyad, mt.ICD10Kodu, count(mi.ID) as AASayisi 
from Muayene.Muayene mm
join Muayene.Ilac mi on mm.ID = mi.MuayeneId
join Yetkilendirme.Users yu on mi.CreatedBy = yu.ID
join Muayene.Tani mt on mm.ID = mt.MuayeneId
where mm.IsDeleted <> 1 and mi.IsDeleted <> 1 and mt.IsDeleted <> 1  
group by yu.ID,yu.Soyad, mt.ICD10Kodu) miCountsQuery inner join (select yu.ID as YUID,yu.Soyad, count(mm.ID) as MMSayisi 
from Muayene.Muayene mm
join Yetkilendirme.Users yu on mm.CreatedBy = yu.ID
where mm.IsDeleted <> 1  
group by yu.ID,yu.Soyad) mmCountsQuery ON miCountsQuery.YUID = mmCountsQuery.YUID

查询未经过测试。可能需要进行一些修改。

答案 1 :(得分:0)

您需要在已加入的查询中执行COUNT操作,而不是在SELECT列表中进行查询。 SELECT列表中的查询不起作用,除非您正在提取1个值,而您在此处未执行此操作。此外,您不能对导出的值(例如COUNT())在您导出它们的同一查询中执行数学运算。

因此,要计算您的费率,您可以执行以下操作,然后使用ID

将其加入到您需要的任何其他内容中
select 
    a.mi_ID as ID
    , a.ct_mi / b.ct_mm as Rate
from
    (select
        mi.ID as mi_ID
        , count(mi.ID) as ct_mi
    from  [Muayene.Ilac] as mi
    group by mi.ID) as a
inner join
    (select
        mm.ID as mm_ID
        , count(mm.ID) as ct_mm
    from [Muayene.Muayene] as mm
    group by mm.ID) as b
on a.mi_ID = b.mm_ID