我有5张与亲子关系的桌子
在父子关系中,我的意思是(userInfo的recordId是UserInfo中的主键,UserInformation和UserEntryEntry中的外键,在下表中保持相同的关系) 我必须做出一个视图,在该视图中我应该重新聚集所有这五个表的记录数据。 主要问题是:
1.IN UserInformation我有重复的数据,我想那不是因为它有关于用户的预注册,注册和编辑信息的记录,并且除了date之外,它们没有其他任何值,在我尝试使用的以下代码中max(datetime)但似乎不起作用,w 我应该怎么做 解决此重复问题?
图片上的这是我表的原始数据示例以及所需结果: enter image description here
创建视图UserRecords 如 选择区域
,ISNULL(DeclInf.ID,'') AS Guid
,ISNULL(DeclInf.UserNumber,'') AS UserNumber
,ISNULL(DeclInf.UserType,'') AS UserType
,ISNULL(DeclInf.CustomerId,'') AS CustomerID
,'' AS CustomerName
,CONVERT(DATETIME,(SELECT MAX(ISNULL(Record.DocumentDate,'')) FROM [UserInformation] Document WITH (NOLOCK)
WHERE Document.DeclarationInformationGUID = DeclInf.DeclarationInformationGUID
GROUP BY Document. ID),104) AS registrationDate
,ISNULL([Entry].TypeOfProduct,'') AS ModeOfProduct
,SUM(ProductWeigtCalculate.Weight) AS TotalDeclarationValue
,SUM(ProductTaxCalculate. Payments) AS TotalPayments
FROM [UserInfo] Incoming WITH (NOLOCK)
LEFT JOIN [UserInformation] DeclInf WITH (NOLOCK)
ON DeclInf.IncomingGUID = Incoming.IncomingGUID
LEFT JOIN [UserEntryEntry] [Entry] WITH (NOLOCK)
ON [Entry].DeclarationInformationGUID = DeclInf.DeclarationInformationGUID
LEFT JOIN (
SELECT DeclInf. GUID AS InformationGUID
,(ISNULL(UserBusket.Amount,0) + (DeclInf.CounterveilingDuty * (ISNULL(UserBusket.StatisticalValue,0) / ISNULL(NULLIF(UserBusket.SumStatisticalValue,0),1)))) AS ProductWeigtCalculate
FROM [UserInformation] DeclInf WITH (NOLOCK)
LEFT JOIN [UserEntryEntry] [Entry] WITH (NOLOCK)
ON [Entry]. InformationGUID = DeclInf. InformationGUID AND
LEFT JOIN (
SELECT DeclarationInformationGUID, SUM(StatisticalValue) AS SumStatisticalValue
FROM [UserEntryEntry]
GROUP BY InformationGUID, PartnerID) EntrySum
ON EntrySum. InformationGUID = DeclInf. InformationGUID
LEFT JOIN(
SELECT DeclInf. InformationGUID AS InformationGUID
,(ISNULL(Tax10.Amount,0) + (DeclInf. Duty * (ISNULL([Entry].StatisticalValue,0) / ISNULL(NULLIF(EntrySum.SumStatisticalValue,0),1)))
+ ISNULL(Tax.Amount,0) + ISNULL(Tax.Amount,0) + ISNULL(Tax.Amount,0)
+ ISNULL([Entry].LocalPortExpenses,0) + ISNULL([Entry].OtherLocalExpenses,0)
+ ISNULL([Entry].FreightAmount,0) + ISNULL([Entry].InsuranceAmount,0)
+ ISNULL([Entry].TresspassingFeeAtTheBorder,0)) AS Payments
FROM [UserInformation] DeclInf WITH (NOLOCK)
LEFT JOIN [UserEntryEntry] [Entry] WITH (NOLOCK)
ON [Entry]. InformationGUID = DeclInf. InformationGUID
GROUP BY DeclInf.DeclarationInformationGUID
,DeclInf.InformationGUID
,DeclInf.Tax
答案 0 :(得分:0)
基于对[UserInformation]表的解释,似乎有多种类型的事务存储为行,以进行预注册,注册和编辑信息。
我不确定您拥有的数据集,但是假设[UserInformation]中每个用户至少有一条记录,如果这样的话,我们可以将其更改为INNER JOIN而不是LEFT OUTER。
根据要从具有预注册,注册和编辑信息的用户那里得到的输出,您必须执行另一个加入过滤条件,如
,SUM(ProductTaxCalculate. Payments) AS TotalPayments
FROM [UserInfo] Incoming WITH (NOLOCK)
INNER JOIN [UserInformation] DeclInf WITH (NOLOCK)
ON DeclInf.IncomingGUID = Incoming.IncomingGUID
AND transactiontype ='pre-registration'
我认为您应该将AND transactiontype ='pre-registration'标识为其他列。