我有一个SQL查询,它正在从多个表中提取数据(我有11个加入)
有一个" artransaction"表,其中包含电荷,付款,调整等。并且其中有一个" TrassActionCodeid"列,其中描述了交易类型。
我正在尝试选择大量数据,但需要两个单独的列(上面有注释),一个用于费用,另一列用于付款。有没有办法在不使用Where子句的情况下实现这一目标?我尝试使用嵌套的选择语句,但它返回了每个行的相同值(总数)
我正在附上以下查询 - 预先感谢!同样,我是数据检索的新手,因此,如果其他任何事情看起来很不奇怪,其他任何建议都非常感谢。
SELECT CONVERT(varchar(10),sl.ServiceDtFrom, 101) AS 'srvdate'
, f.Alias AS 'svc dprtmnt'
, CASE WHEN pc.Alias IS NULL
THEN po.Name
ELSE pc.Description END AS 'svc dept grp'
, COUNT(clm.ID) AS 'clm cnt'
, COUNT(p.ID) AS 'ptnt count'
/* 1 */
, SUM(ar.Amount) AS 'all chgs' --ONLY CHARGES (tt.ID IN(1,2))
, SUM(sl.Units + sl.TimeUnits + sl.PhysicalStatusUnits) AS 'chg units sum'
/* 2 */
, SUM(ar.Amount) AS 'net pmt' --ONLY PAYMENTS (tt.ID IN(3,4,9,10,11,12,20,21))
FROM ARTransaction ar WITH (NOLOCK)
LEFT JOIN ServiceLine sl WITH (NOLOCK)
ON ar.ServiceLineID = sl.ID
LEFT JOIN Incident i WITH (NOLOCK)
ON sl.IncidentID = i.ID
LEFT JOIN HealthCareFacility f WITH (NOLOCK)
ON i.FacilityID = f.ID
LEFT JOIN ProvOrgFacility poc WITH (NOLOCK)
ON poc.FacilityID = f.ID
LEFT JOIN ProfitCenter pc WITH (NOLOCK)
ON poc.ProfitCenterID = pc.ID
LEFT JOIN ProviderOrganization po WITH (NOLOCK)
ON i.ProvOrgID = po.ID
LEFT JOIN Claim clm WITH (NOLOCK)
ON i.ID = clm.IncidentID
LEFT JOIN Person p WITH (NOLOCK)
ON i.PatientID = p.ID
LEFT JOIN TransactionCode tc WITH (NOLOCK)
ON ar.TransactionCodeID = tc.ID
LEFT JOIN TransactionType tt WITH (NOLOCK)
ON tc.TransactionTypeID = tt.ID
WHERE i.IsReversed <> 1
AND sl.ServiceDtFrom IS NOT NULL
GROUP BY
sl.ServiceDtFrom, f.Alias
, po.Name, pc.Alias, pc.Description
ORDER BY 1,3,2
您可以使用案例语句来实现这一目标: -
SELECT CONVERT(varchar(10),sl.ServiceDtFrom, 101) AS 'srvdate'
, f.Alias AS 'svc dprtmnt'
, CASE WHEN pc.Alias IS NULL
THEN po.Name
ELSE pc.Description END AS 'svc dept grp'
, COUNT(clm.ID) AS 'clm cnt'
, COUNT(p.ID) AS 'ptnt count'
/* 1 */
, SUM(case when tt.ID IN(1,2) then ar.Amount else 0 end) AS 'all chgs' --ONLY CHARGES (tt.ID IN(1,2))
, SUM(sl.Units + sl.TimeUnits + sl.PhysicalStatusUnits) AS 'chg units sum'
/* 2 */
, SUM(case when tt.ID IN(3,4,9,10,11,12,20,21) then ar.Amount else 0 end) AS 'net pmt' --ONLY PAYMENTS (tt.ID IN(3,4,9,10,11,12,20,21))
FROM ARTransaction ar WITH (NOLOCK)
LEFT JOIN ServiceLine sl WITH (NOLOCK)
ON ar.ServiceLineID = sl.ID
LEFT JOIN Incident i WITH (NOLOCK)
ON sl.IncidentID = i.ID
LEFT JOIN HealthCareFacility f WITH (NOLOCK)
ON i.FacilityID = f.ID
LEFT JOIN ProvOrgFacility poc WITH (NOLOCK)
ON poc.FacilityID = f.ID
LEFT JOIN ProfitCenter pc WITH (NOLOCK)
ON poc.ProfitCenterID = pc.ID
LEFT JOIN ProviderOrganization po WITH (NOLOCK)
ON i.ProvOrgID = po.ID
LEFT JOIN Claim clm WITH (NOLOCK)
ON i.ID = clm.IncidentID
LEFT JOIN Person p WITH (NOLOCK)
ON i.PatientID = p.ID
LEFT JOIN TransactionCode tc WITH (NOLOCK)
ON ar.TransactionCodeID = tc.ID
LEFT JOIN TransactionType tt WITH (NOLOCK)
ON tc.TransactionTypeID = tt.ID
WHERE i.IsReversed <> 1
AND sl.ServiceDtFrom IS NOT NULL
GROUP BY