我有一个包含以下列的表
email, id, date
电子邮件地址ID上有一个唯一的密钥,因此该表格可以包含多个电子邮件地址。 id可以为null。
我想以格式
返回结果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(日期),前提是它们的条目非空id
如果没有id,有什么方法可以使MIN(日期)无效吗?我正在开发一个解决方案,如果id为0并且得到MIN的MIN,那么date
会增加很多天,但似乎必须有一个更聪明的方法?
答案 0 :(得分:4)
您需要条件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])
答案 1 :(得分: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])