1

我有一个包含以下列的表格

email, id, date 

email+id 上有一个唯一键,因此该表可以包含多个电子邮件地址。id 可以为空。

我想以格式返回结果

email, first date, number of ids, first id date (if number of ids not null) 

或者

dave@myfirm.con, 2013-06-11, 0, NULL
alan@myfirm.con, 2013-06-12, 2, 2013-06-13

我的查询非常接近我想要的,同时仍然有效。

SELECT TOP (@rows * @page) email, MIN([date]) as [date],COUNT(id) as [ids],
[x] = CASE COUNT(id) WHEN 0 THEN NULL ELSE MIN([date]) END
FROM Table 
GROUP BY email ORDER by MIN([date])

但是,此版本的查询返回每封电子邮件的总体 MIN(date),如果它们有任何非空条目id

如果没有 id,有什么方法可以取消 MIN(date) 吗?我正在研究一个解决方案,如果 id 为 0 并获得它的 MIN 则增加大量天数date,但似乎必须有更聪明的方法?

4

2 回答 2

7

你想要一个有条件的min(),所以case在里面使用min()

SELECT TOP (@rows * @page) email,
       MIN([date]) as [date],
       COUNT(id) as [ids],
       min(case when id is not null then [date] end) as [x]
FROM Table 
GROUP BY email
ORDER by MIN([date])
于 2013-06-13T15:27:58.217 回答
0

尝试这个

SELECT TOP (@rows * @page) email, MIN([date]) as [date],COUNT(id) as [ids],
[x] = (SELECT MIN([date]) FROM table t2 WHERE t2.email = t.email and t2.id IS NOT NULL) 
FROM Table t
GROUP BY email ORDER by MIN([date])
于 2013-06-13T15:05:19.510 回答