SQL Server:从每个选项中选择至少一个mach

时间:2016-08-21 15:45:36

标签: sql sql-server

我需要从'com.android.tools.build:gradle:2.2.0-beta2'中选择Property

中每个Pid至少1个

属性

UserData

的UserData

Pid  OptId
----------
5     12 
5     13
5     14
6     22
6     23
7     28
7     29

结果应该是:

UId Pid OptId
---------- 
1   5   13
1   6   23
1   7   28
2   5   12
2   6   22

结果仅显示UId Pid OptId ------------- 1 5 13 1 6 23 1 7 28 的行,因为每个属性(5,6,7)至少有一个Uid=1Pid未包含在结果中,因为它有Uid=2但没有pid = 5 & 6

有可能吗?

4 个答案:

答案 0 :(得分:2)

<强> https://github.com/mspapant/restVersioningExample/

首先,你需要知道有多少属性

 SELECT COUNT(DISTINCT Pid) as total_properties
 FROM Property

然后,您需要查看每个UserData

有多少属性
SELECT u.UId, count(DISTINCT u.Pid) as Uid_property
FROM UserData u
GROUP BY u.UId

然后一起加入

SELECT *
FROM UserData u
JOIN (
    SELECT u.UId, count(DISTINCT u.Pid) as Uid_property
    FROM UserData u
    GROUP BY u.UId
    ) t1
  ON u.UId = t1.UId
CROSS JOIN (
    SELECT COUNT(DISTINCT Pid) as total_properties
    FROM Property
   ) t2
WHERE t1.Uid_property = t2.total_properties

<强>输出

SQL Demo

答案 1 :(得分:1)

这被称为关系分裂。使用NOT EXISTS查询

SELECT *
FROM Userdata ud1
WHERE NOT EXISTS
       (SELECT pId
          FROM Property p
          WHERE NOT EXISTS
               (SELECT 1
                FROM Userdata ud2
                WHERE ud2.UId = ud1.UId
                   AND ud2.pId = p.pId));

查看更多选项 https://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/

答案 2 :(得分:0)

这假设uid的组合,pid在userdata中是唯一的

;wITH CTE
AS
(select UId,Pid,OptId,COUNT(PID) OVER (PARTITION BY UID) AS CNT
 from #userdata u
 )
 SELECT UID,PID,OPTID FROM CTE
 WHERE CNT=(SELECT COUNT(DISTINCT PID) FROM #PROPERTY)

答案 3 :(得分:0)

需要确保数据和属性中pid的数量。

;WITH cte_cntUserdata
 AS
  (SELECT UId,PId,OptId,COUNT(PId) OVER (PARTITION BY UID) AS Cnt_Pid
   FROM Userdata u
   WHERE EXISTS (SELECT 1 
                               FROM Property p 
                               WHERE u.Pid=p.Pid and u.optId=p.optId)
                                )
  SELECT UId,PId,OptId 
  FROM cte_cntUserData 
  WHERE Cnt_Pid=(SELECT COUNT(DISTINCT PId) FROM Property)