如何根据条件对表中的值进行分组

时间:2015-02-13 19:12:48

标签: sql sql-server sql-server-2008

我有一个表格,其值如下:

MemberID    Location        DateJoined
79925        183            2013-07-01 00:00:00.000 
79925        184            2013-07-02 00:00:00.000
65082        184            2012-07-22 00:00:00.000
72046        183            2013-05-01 00:00:00.000 
72046        184            2013-05-10 00:00:00.000 
...

这里我需要检查上表是否有locationID 183& 184.
基于这些结果,我需要创建一个新表,如下所示

MemberID    Benifit
79925        Yes
65082        No
72046        Yes

3 个答案:

答案 0 :(得分:2)

如果我理解你的话

select MemberID, case when Sum(x) = 2 then 'YES' else 'No' end Benifit from
(
  SELECT *, CASE WHEN Location in (183,184) THEN 1 ELSE 0 END AS x
  FROM MyTable
) t
group t by MemberID

答案 1 :(得分:1)

INSERT INTO table2 (MemberID, Benifit)
SELECT t1.MemberID, 
CASE WHEN t2.MemberID IS NULL OR t3.MemberID IS NULL THEN 'NO' ELSE 'YES' END AS Benefit
FROM table1 t1
 LEFT JOIN table1 t2 ON (t2.MemberID = t1.MemberID AND t2.Location = 183)
 LEFT JOIN table1 t3 ON (t3.MemberID = t1.MemberID AND t3.Location = 184)
WHERE t1.Location IN (183,184)
GROUP BY t1.MemberID, t2.MemberID, t3.MemberID

http://sqlfiddle.com/#!3/ece758/7

答案 2 :(得分:1)

看起来您想要显示位置为183 184的所有成员。您可以执行以下操作:

INTERSECT子查询将返回与183和184位置相关联的所有MemberID,CASE将显示是或否。

SELECT
  MemberID,
  CASE
   WHEN MemberID IN
    (SELECT MemberID FROM Table WHERE Location = 183
     INTERSECT
     SELECT MemberID FROM Table WHERE Location = 184)
     THEN 'Yes' ELSE 'No' END as 'Benefit'
FROM Table

只需使用WHERE Location in (183,183)即可显示位于任意位置的会员ID,但不一定都是。