首先我要说的是,我是SQL新手,每天都在学习。话虽如此,这是我的问题。我有一个已经创建的视图(它显示了设备上产生的收入),但我需要再添加一个表(对设备的费用)。当我尝试添加内部联接表时,它会创建一堆重复的视图。这是我原来的观点(对于它的收入部分):
SELECT
<removed, there are about 25 of them>
FROM
dbo.LRCON WITH (nolock)
INNER JOIN dbo.LRCONVIN WITH (nolock) ON dbo.LRCONVIN.ConId = dbo.LRCON.ConId
INNER JOIN dbo.LRBILCON WITH (nolock) ON dbo.LRBILCON.ConId = dbo.LRCONVIN.ConId AND dbo.LRBILCON.UntId = dbo.LRCONVIN.UntId
INNER JOIN dbo.LRBILITM WITH (nolock) ON dbo.LRBILITM.ParentItmId = dbo.LRBILCON.ItmId
INNER JOIN dbo.LRBIL WITH (nolock) ON dbo.LRBIL.BilId = dbo.LRBILCON.BilId
INNER JOIN dbo.LRCONTYP WITH (nolock) ON dbo.LRCONTYP.ConTypId = dbo.LRCON.ConTypId
INNER JOIN dbo.COLOOKUP AS C1 WITH (nolock) ON C1.Id = dbo.LRBILITM.ItmTyp
INNER JOIN dbo.COLOOKUP AS C2 WITH (nolock) ON C2.Id = dbo.LRCONTYP.ConTyp
INNER JOIN dbo.VHVIN WITH (nolock) ON dbo.VHVIN.UntId = dbo.LRCONVIN.UntId
WHERE
(dbo.LRBIL.Status = 647) AND (dbo.LRBILITM.ItmTyp <> 274)
然后我尝试添加另一个连接:
INNER JOIN dbo.SVSLS WITH (nolock) on dbo.SVSLS.UntId = dbo.LRCONVIN.UntId
使用select语句:
ROUND(dbo.SVSLS.AmtSubtotal + dbo.SVSLS.AmtSupplies + dbo.SVSLS.AmtDiagnostic + dbo.SVSLS.AmtTax1 + dbo.SVSLS.AmtTax2, 2) AS SvcAmtSale
...但它会产生许多行的重复项,因为它会将每个费用的详细信息添加到原始表的每一行。
原始表: https://dl.dropboxusercontent.com/u/81145403/orginal_table.jpg
添加新的加入/选择后: https://dl.dropboxusercontent.com/u/81145403/failed_table.jpg
我该如何解决这个问题?在一天结束时,我只想比较我在一个日期范围内的设备收入与费用。我真的不在乎拥有费用的个别细节,只是总的来说对我很好。
答案 0 :(得分:1)
SvcSaleAmt是您感兴趣的收入吗?并且多个详细信息行是否在同一项上分隔条目?如果您不一定关心个别详细信息,可以将项目组合在一起。为此,您需要从SELECT列表中删除SlsId,然后添加
GROUP BY CusId, CusName, BillId, ConId, Prd, ConTypId, ....., AmtCos, AmtGpm
使用SELECT语句中的所有列。将ROUND()AS SvcSaleAmt替换为:
ROUND(SUM(dbo.SVSLS.AmtSubtotal + dbo.SVSLS.AmtSupplies + dbo.SVSLS.AmtDiagnostic + dbo.SVSLS.AmtTax1 + dbo.SVSLS.AmtTax2), 2) AS SvcSaleAmt