SQL需要确定数据集中的id

时间:2014-06-19 18:55:48

标签: sql-server tsql join

在给定以下数据集和规则的情况下,我无法得到一个合理的SQL,它将返回所需的id。返回的id应为1,5和6。

规则1 - 如果酒精和药物类别都存在并且酒精<= 3且药物=否

,则返回ID

规则2 - 如果仅存在酒精类别且酒精<= 3

,则返回ID

规则3 - 如果仅存在药物类别且药物=否

,则返回ID
id  Category Value
1   Alcohol  0
1   Drug     No
2   Alcohol  5
2   Drug     Yes
3   Alcohol  3
3   Drug     Yes
4   Alcohol  5
4   Drug     No
5   Alcohol  2
6   Drug     No
7   Alcohol  5
8   Drug     Yes

提前致谢。

select
    dt.id
from
(
    select
        id as id
    from
        @datatbl
    group by
        id
    having
        count(*) = 1
) X
inner join @datatbl dt on
    dt.id = X.id
where
    dt.value in ('0', '1', '2', '3', 'No')
union
select
    dt1.id
from
    @datatbl dt1
    inner join (
        select
        dt.id
        from
        (
            select
                id as id
            from
                @datatbl
            group by
                id
            having
                count(*) = 2
        ) X
        inner join @datatbl dt on
            dt.id = X.id
        where
            dt.category = 'Alcohol'
            and
            dt.value in ('0', '1', '2', '3')
    ) X on
        X.id = dt1.id
where
    dt1.category = 'Drug'
    and
    dt1.value in ('No')

1 个答案:

答案 0 :(得分:1)

<强>的Rule1:

SELECT *
FROM MyTable t1
INNER JOIN MyTable t2 ON t1.id = t2.id 
  AND t1.Category <> t2.Category AND t2.Category = 'Drug'
WHERE t1.Category = 'Alcohol' AND t1.Value <= 3 AND t2.Value = 'No'

<强>规则2:

SELECT *
FROM MyTable t1
LEFT JOIN MyTable t2 ON t1.id = t2.id 
  AND t1.Category <> t2.Category AND t2.Category = 'Drug'
WHERE t1.Category = 'Alcohol' AND t1.Value <= 3 AND t2.Category IS NULL

<强>规则3:

SELECT *
FROM MyTable t1
RIGHT JOIN MyTable t2 ON t1.id = t2.id 
  AND t1.Category <> t2.Category AND t2.Category = 'Drug'
WHERE t2.Value = 'No' AND t1.Category IS NULL