更新了问题。我有以下表格: 项目表 projectid,项目
存储表 STOREID,STORENAME,专案编号
projectupdates表 trackerid,projectid,storeid,activityid,date
活动表 活动,活动
项目可能有也可能没有商店 商店可能有也可能没有活动 对于商店,可以重复活动
有了这个,我想要所有的项目,所有的 商店的商店和更新。
活动(如果有)应仅显示 活动的最新日期。
我还想要一个对每个进行计数的摘要行 活动有日期的活动。 (如果为null 不要算。)
我尝试了以下代码:
SELECT P.ProjectID, S.StoreID, MAX(CASE WHEN Activity = 'Meas Perm Received' THEN Date ELSE NULL END) AS MeasPermRcvd, MAX(CASE WHEN Activity = 'Not Visited' THEN Date ELSE NULL END) AS NotVisited, MAX(CASE WHEN Activity = 'Not Visited' THEN ReasonID ELSE '' END) AS NotVisitedReason, MAX(CASE WHEN Activity = 'Visited & Measured' THEN Date ELSE NULL END) AS Measured
FROM dbo.ProjectUpdates AS T INNER JOIN dbo.Project AS P ON T.ProjectID = P.ProjectID INNER JOIN dbo.ProjectStores AS S ON T.StoreID = S.StoreID INNER JOIN dbo.Activity AS A ON T.ActivityID = A.ActivityID GROUP BY P.ProjectID,S.StoreID
然后我尝试使用这个额外的查询来获取所有项目和商店:
SELECT dbo.Project.ProjectID, dbo.ProjectStores.StoreID,dbo.StoreTrackerBase.MeasPermRcvd, dbo.StoreTrackerBase.NotVisited, dbo.StoreTrackerBase.NotVisitedReason, dbo.StoreTrackerBase.Measured
FROM dbo.Project FULL OUTER JOIN dbo.ProjectStores ON dbo.Project.ProjectID = dbo.ProjectStores.ProjectID FULL OUTER JOIN dbo.StorTrackerBase ON dbo.ProjectStores.StoreID = dbo.StoreTrackerBase.StoreID AND dbo.ProjectStores.ProjectID = dbo.StoreTrackerBase.ProjectID
这将返回所有项目和所有具有最新活动日期的商店。 请告知这是否是良好的编码方式以及性能是否良好。
请注意我在此查询中没有摘要行(不知道该怎么做!) 谢谢。克里希纳
答案 0 :(得分:0)
您可以将MAX(CASE WHEN Activity = 'ActivityType' THEN Date END)
与Group by ProjectName,Store
SELECT
ProjectName,Store,
MAX(CASE WHEN Activity = 'Visited' THEN Date ELSE NULL END) AS Visited,
MAX(CASE WHEN Activity = 'NotVisited' THEN Date ELSE NULL END) AS NotVisited,
MAX(CASE WHEN Activity = 'Finished' THEN Date ELSE NULL END) AS Finished
FROM Table1 T
INNER JOIN Project P
ON T.ProjectID = P.ProjectID
INNER JOIN Store S
ON T.StoreID = S.StoreID
INNER JOIN Activity A
ON T.ActivityID = A.ActivityID
GROUP BY ProjectName,Store