[英]Different values of column 1 based on column 2 SQL Server
I have a table with columns ID
and Val
. 我有一个带有ID
和Val
列的表。 For each value of ID
we can have either same or different values of Val
. 对于每个ID
值,我们可以具有相同或不同的Val
值。
ID Val
1 A
1 NULL
2 00
2 00
2 00
2 00
3 00
3 A
4 A
5 00
5 00
5 A
6 A
6 A
6 NULL
6 00
From above table, I am looking for IDs which has different values in Val column. 从上表中,我正在寻找在Val列中具有不同值的ID。 If for any given ID all values of Val column are same then it should not come in result. 如果对于任何给定的ID,Val列的所有值都相同,则不应得出结果。
So result would be something like. 因此结果将是类似的。
D Val
1 A
1 NULL
3 00
3 A
5 00
5 00
5 A
6 A
6 A
6 NULL
6 00
Id 2 should not come in result because for Id 2, Val column has same data. Id 2不应出现在结果中,因为对于Id 2,Val列具有相同的数据。 Similarly ID 4 will not come in result as ID 4 has only one row. 同样,由于ID 4只有一行,因此不会出现ID 4的结果。
For each ID if we have more than one value in Val column then is it should show in result. 对于每个ID,如果我们在Val列中有多个值,那么它应该显示在结果中。
Thanks for the Help! 谢谢您的帮助!
For the ids that meet the condition of having different values: 对于满足具有不同值条件的ID:
select id
from t
group by id
having min(id) <> max(id);
You can then incorporate this into a query as: 然后可以将其合并到查询中,如下所示:
select t.*
from t join
(select id
from t
group by id
having min(id) <> max(id)
) tt
on t.id = tt.id;
Or, you can use window functions: 或者,您可以使用窗口功能:
select t.id, t.val
from (select t.*,
min(val) over (partition by id) as minval,
max(val) over (partition by id) as maxval
from t
) t
where minval <> maxval;
Try this: 尝试这个:
SELECT ID, Val
FROM mytable
WHERE ID IN (SELECT ID
FROM mytable
GROUP BY ID
HAVING COUNT(DISTINCT CASE
WHEN Val IS NULL THEN ''
ELSE Val
END) > 1
I've made the assumption that Val
field is of type VARCHAR
and that it can be either NULL
or <> ''
. 我假设Val
字段是VARCHAR
类型,并且可以是NULL
或<> ''
。
Build your query at three steps: 通过三个步骤构建查询:
Try to use inner select instead of subselect to speed up the query. 尝试使用内部选择而不是子选择来加快查询速度。
The solution is written in the query below: 解决方案写在下面的查询中:
SELECT
t.*
FROM
-- select only ids with distinct count > 1
(
SELECT
id
FROM
-- select distinct values to ensure your count of null values is real
(
SELECT DISTINCT
id, val
FROM
t
) AS td
GROUP BY
id
HAVING
COUNT(*) > 1
) AS tc
-- join the source table
INNER JOIN
t
ON
t.id = tc.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.