You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL Server多表场景下,如何查询某列含多个特定值的行?

Solution for Querying Rows with Multiple Specific Values in SQL Server

Hey there! I get it, hunting for the right SQL Server query to find rows where a column includes multiple specific values can be tricky—especially when you’ve already scoured Google and YouTube without luck. Let’s break this down based on common scenarios you might be dealing with, using your STUDENTS table as an example.

Scenario 1: The column stores delimited values (e.g., comma-separated)

Suppose your STUDENTS table has a column like ENROLLED_COURSES that holds values such as 'MATH101,ENG202,PHY303', and you need to find students who are enrolled in both MATH101 and ENG202.

Option 1: Using CHARINDEX (simple but less strict)

This works if you’re confident there’s no partial value overlap (e.g., no course code like MATH1010 that would match MATH101):

SELECT PERSON_ID, ENROLL_PERIOD, ENROLLED_COURSES
FROM STUDENTS
WHERE CHARINDEX('MATH101', ENROLLED_COURSES) > 0
  AND CHARINDEX('ENG202', ENROLLED_COURSES) > 0;

Option 2: Using STRING_SPLIT (more robust, SQL Server 2016+)

This splits the delimited column into rows, then checks if all required values are present:

SELECT s.PERSON_ID, s.ENROLL_PERIOD, s.ENROLLED_COURSES
FROM STUDENTS s
CROSS APPLY STRING_SPLIT(s.ENROLLED_COURSES, ',') AS split_courses
WHERE split_courses.value IN ('MATH101', 'ENG202')
GROUP BY s.PERSON_ID, s.ENROLL_PERIOD, s.ENROLLED_COURSES
HAVING COUNT(DISTINCT split_courses.value) = 2; -- Match the number of specific values you need

Scenario 2: Joining two tables to find matching rows

If you’re working with a second table (e.g., ENROLLMENTS that links students to courses via PERSON_ID), and you need to find students enrolled in all specified courses:

SELECT s.PERSON_ID, s.ENROLL_PERIOD
FROM STUDENTS s
JOIN ENROLLMENTS e ON s.PERSON_ID = e.PERSON_ID
WHERE e.COURSE_CODE IN ('MATH101', 'ENG202')
GROUP BY s.PERSON_ID, s.ENROLL_PERIOD
HAVING COUNT(DISTINCT e.COURSE_CODE) = 2; -- Again, match the number of target values

Quick note for "any of the values"

If you actually need rows where the column includes any of the specific values (not all), it’s simpler:

SELECT PERSON_ID, ENROLL_PERIOD
FROM STUDENTS
WHERE your_target_column IN ('value1', 'value2');

Adjust the column names and values to match your actual schema, and let me know if you need tweaks for your exact use case!

内容的提问来源于stack exchange,提问作者poetry emo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:14:13