查找具有两个以上元素的用户,其中一个元素必须为A.

时间:2016-10-18 16:44:10

标签: sql sql-server tsql

我想提取具有两个以上元素的用户,其中一个元素必须是A

这是我的表:

CREATE TABLE #myTable(
    ID_element nvarchar(30),
    Element nvarchar(10),
    ID_client nvarchar(20)
)

这是我桌子的数据:

INSERT INTO #myTable VALUES
(13 ,'A', 1),(14 ,'B', 1),(15 ,NULL, 1),(16 ,NULL, 1),
(17 ,NULL, 1),(18 ,NULL, 1),(19 ,NULL, 1),(7, 'A', 2),
(8, 'B', 2),(9, 'C', 2),(10 ,'D', 2),(11 ,'F', 2),
(12 ,'G', 2),(1, 'A', 3),(2, 'B', 3),(3, 'C', 3),
(4, 'D', 3),(5, 'F', 3),(6, 'G', 3),(20 ,'Z', 4),
(22 ,'R', 4),(23 ,'D', 4),(24 ,'F', 5),(25 ,'G', 5),
(21 ,'x', 5)

这是我的疑问:

Select Distinct  ID_client
from #myTable
Group by ID_client
Having      Count(Element) > 2

3 个答案:

答案 0 :(得分:2)

添加到您的查询CROSS APPLY与const userIdsFilter = [1,2]; //find Conversations that have user 1 OR user 2 as participants, Conversation.findAll({ include : [{ model : ConversationParticipant, as : 'conversation_participants', where : { userId : { $in: userIdsFilter }} }] }).then((conversations) => { //filter the conversations that have the same length participants //as the userIdsFilter length (that way it excludes the ones //that have just one of the users as participants) return conversations.filter((conversation) => conversation.conversation_participants.length === userIdsFilter.length); }).then((conversations) => { //do what you need with conversations.. }) s有元素id_client

A

输出:

SELECT m.ID_client
FROM #myTable m
CROSS APPLY (
    SELECT ID_client
    FROM #myTable
    WHERE ID_client = m.ID_client
        AND Element = 'A'
    ) s
GROUP BY m.ID_client
HAVING COUNT(DISTINCT m.Element) > 2

答案 1 :(得分:0)

我认为这就是你要找的东西:

my_array = *"A".."Z"
  #=> ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
  #    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] 

带回来

SELECT * FROM 
(SELECT *, RANK() OVER (PARTITION BY element ORDER by id_client) AS grouped FROM #myTable)  t 
wHERE grouped > 1
AND Element = 'A'
ORDER by t.element

答案 2 :(得分:0)

您可以选择{A}作为ID_client的{​​{1}}值,并将结果加入您的表格中:

Element

输出:

SELECT m.ID_Client
FROM #myTable AS m
JOIN (
      SELECT a.ID_Client FROM #myTable AS a
      WHERE a.Element = 'A') AS filteredClients
ON m.ID_client = filteredClients.ID_client
GROUP BY m.ID_client
HAVING COUNT(m.Element) > 2

然而,这不一定是最好的方法:When should I use Cross Apply over Inner Join?