在数据子集上编写具有多种变化条件的查询

时间:2018-08-10 00:22:06

标签: sql sql-server

我正在编写一个查询,该查询搜索每个MailID并选择具有关联的ActivityId 3但没有关联的ActivityId 7的ActivityId 1。

这是示例结果集:

MailID | ActivityId
==============
155311406 | 1
154733588 | 3
154733588 | 1
154733588 | 7
154723283 | 1
154699790 | 1
154692365 | 7
154692365 | 1
154692365 | 3
154685546 | 7
154685546 | 1
154685546 | 3
154093013 | 1
153921107 | 3
153921107 | 7
153921107 | 1
153920994 | 3
153920994 | 1
153920932 | 7
153920932 | 3
153920932 | 1

我尝试查询,但是没有得到正确的输出:

SELECT MailId, ActivityId
INTO #temp
FROM Mail WITH(NOLOCK)
WHERE ActivityId IN (1, 3, 7)


SELECT MailID
FROM Mail M
WHERE EXISTS (SELECT 1 FROM #temp T WHERE T.vNettId = M.vNettID AND T.ActivityId = 3)
AND NOT EXISTS (SELECT 1 FROM #temp T WHERE T.vNettId = M.vNettID AND T.ActivityId = 7)
AND M.ActivityId = 1

对于此查询的任何帮助将不胜感激

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用group byhaving进行查询。

SELECT MailId
FROM Mail 
WHERE ActivityId IN (1, 3, 7)
GROUP BY MailId
HAVING COUNT(DISTINCT CASE WHEN ActivityId IN (1,3) THEN ActivityId END)=2
AND COUNT(DISTINCT CASE WHEN ActivityId = 7 THEN ActivityId END)=0

答案 1 :(得分:1)

您可以这样写:

SELECT MailId
FROM Mail 
WHERE ActivityId IN (1, 3, 7)
GROUP BY MailId
HAVING MIN(ActivityId) = 1 AND
       MAX(ActivityId) = 3;

这不是超级概括。一个更通用的方法是:

SELECT MailId
FROM Mail 
WHERE ActivityId IN (1, 3, 7)
GROUP BY MailId
HAVING SUM(CASE WHEN ActivityId = 1 THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN ActivityId = 3 THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN ActivityId = 7 THEN 1 ELSE 0 END) = 0;

答案 2 :(得分:0)

您无法从查询中获得任何结果集,因为vNettID表中未包含似乎用于关联MailID的字段#temp

另一个没有临时表的查询如何呢?

WITH T (vNettID) AS (
  SELECT vNettID
  FROM Mail
  WHERE ActivityID IN (3, 7)
  GROUP BY vNettID
  HAVING SUM(CASE ActivityID WHEN 7 THEN 1 ELSE 0 END) = 0
)
SELECT M.MailID
FROM Mail M 
  INNER JOIN T ON M.vNettID = T.vNettID
WHERE M.ActivityID = 1