GROUP BY有条件

时间:2018-03-15 09:37:29

标签: sql-server

我有一张这样的桌子

accountid (int)
emailaddress (varchar)
email(bit)
postal(bit)
sms(bit)
telephone(bit

accountid是唯一的,但是emailaddress可能有重复,

accountid emailaddress    email postal sms  telephone
62626     test@test.com   0     1      0    1
76364     blah@blah.com   0     0      0    1
37374     test@test.com   NULL  NULL   NULL NULL

我想创建一个按电子邮件地址分组的查询,但是选择电子邮件不为空的记录,如果没有非空记录则可以选择任何一个。

在这个例子中,我希望最终得到

accountid emailaddress    email postal sms  telephone
62626     test@test.com   0     1      0    1
76364     blah@blah.com   0     0      0    1

这可能吗?

由于

2 个答案:

答案 0 :(得分:0)

确定。我的理解是你想要电子邮件地址不为空的记录,这些字段(电子邮件,邮政,短信,电话)的任何字段值都不应为空。然后试试这个:

Select * 
from yourtable 
where emailaddress is not null 
  and (email is not null 
       AND postal is not null 
       AND sms is not null 
       AND telephone is not null)
Group By emailaddress 

答案 1 :(得分:0)

试试这个:

System.Web

<强>输出:

DECLARE @Tab TABLE (accountid INT, emailaddress VARCHAR(50), email INT,  postal INT, sms  INT, telephone INT)
INSERT INTO @Tab VALUES(62626,'test@test.com' ,  0   ,  1    ,  0 ,   1)
INSERT INTO @Tab VALUES(76364,'blah@blah.com' ,  0   ,  0    ,  0 ,   1)
INSERT INTO @Tab VALUES(37374,'test@test.com' ,  NULL   ,  NULL    ,  NULL ,  NULL)
INSERT INTO @Tab VALUES(11111,'null@null.com' ,  NULL   ,  NULL    ,  NULL ,  NULL)

SELECT MAX(CASE WHEN email IS NOT NULL THEN accountid ELSE accountid END) 
    ,emailaddress
    ,MAX(CASE WHEN email IS NOT NULL THEN email ELSE email END) 
    ,MAX(CASE WHEN email IS NOT NULL THEN postal ELSE postal END) 
    ,MAX(CASE WHEN email IS NOT NULL THEN sms ELSE sms END) 
    ,MAX(CASE WHEN email IS NOT NULL THEN telephone ELSE telephone END) 
FROM @Tab
GROUP BY emailaddress