2015-04-01 164 views
0

下面的代碼用相同的項目名稱和不同的日期對多個記錄進行分組。SQL Group by Max Date Including Null

問題是日期字段中的某些日期爲空。我需要這種代碼的方式來包含最大日期或空值。

我嘗試添加或受日期爲空,但那時,只是讓我回到我的問題與具有多個記錄

原始SQL

SELECT t1.Project_Name, t1.IssueNmb, t1.Date 
FROM Milestones_Detail_Report_Table AS t1 
WHERE (((t1.Date)=(SELECT Max(t2.Date) 
    FROM Table_Name t2 
    WHERE t2.Project_Name=t1.Project_Name 
    GROUP BY t2.Project_Name))) 

SQL與OR

SELECT t1.Project_Name, t1.IssueNmb, t1.Date 
FROM Milestones_Detail_Report_Table AS t1 
WHERE (((t1.Date)=(SELECT Max(t2.Date) 
    FROM Table_Name t2 
    WHERE t2.Project_Name=t1.Project_Name 
    GROUP BY t2.Project_Name))) OR (((t1.Date) Is Null)); 

項目表:表名

Project_Name | IssueNmb | Date 
------------------------ 
    Car  | 1  | 1/1/15 
    Car  | 1  | 2/1/15 <--This record populates 
    House  | 1  |  <--This record does NOT populate 
+1

請顯示樣品結果。你是什​​麼意思「我需要一種方法來讓這個代碼包含最大日期或空值」? – 2015-04-01 19:50:23

+0

您可以用默認值替換null,假設:'1899-01-01'。使用'Iif()'函數 – 2015-04-01 19:50:24

回答

1

你可能想這where條款:

WHERE (t1.Date IS NULL) OR 
     (t1.Date = (SELECT iif(COUNT(*) <> COUNT(t2.Date), NULL, Max(t2.Date)) 
        FROM Table_Name t2 
        WHERE t2.Project_Name = t1.Project_Name 
       ) 
    ) 

這將把NULL的最大日期,所以會出現在子查詢沒有匹配如果t2.Date任何值NULL給定項目。

請注意,子查詢中不需要group by

+0

不知道't2'中實際的數據是什麼意思,在子查詢中加入'LIMIT 1' – 2015-04-01 19:58:37

+0

這就是我輸入的內容,並且在表達式中得到了'Unfixed function'iff' SELECT T1.Project_Name,t1.IssueNmb,t1.Date FROM TableName AS t1 WHERE(((t1.Date)is Null or(t1.Date)=(SELECT iff(COUNT(*)<> COUNT(t2。 ()); NULL,Max(t2.Date)) FROM TableName WHERE t2.Project_Name = t1.Project_Name )));' – user4581436 2015-04-01 20:19:46

+1

@ user4581436 ...該函數是'iif()'不是'iff()' 。 – 2015-04-01 22:20:13