Since you did not provide sample data and expected result, just for fun I propose this example to give a hint on how to achieve this using the function STUFF()
CREATE TABLE Teachers
(
TeacherID INT PRIMARY KEY NOT NULL,
TeacherName VARCHAR(45) NOT NULL
);
CREATE TABLE Classes
(
ClassID INT PRIMARY KEY NOT NULL,
Class VARCHAR(45) NOT NULL,
MainTeacher INT NOT NULL,
CONSTRAINT FK_Classes_MainTeacher FOREIGN KEY (MainTeacher) REFERENCES Teachers (TeacherID)
);
INSERT INTO Teachers (TeacherID, TeacherName) VALUES
(1, 'Teacher1'),
(2, 'Teacher2');
INSERT INTO Classes (ClassID, Class, MainTeacher) VALUES
(1, 'Class1', 1),
(2, 'Class2', 1),
(3, 'Class3', 2);
SELECT T.*,
STUFF(
(
SELECT DISTINCT ',' + Class
FROM Classes C
WHERE C.MainTeacher = T.TeacherID
FOR XML PATH('')
), 1, 1, ''
) ControlledClasses
FROM Teachers T ;
Results:
+-----------+-------------+-------------------+
| TeacherID | TeacherName | ControlledClasses |
+-----------+-------------+-------------------+
| 1 | Teacher1 | Class1,Class2 |
| 2 | Teacher2 | Class3 |
+-----------+-------------+-------------------+
Here’s a live demo
db<>fiddle demo
And what would be the desired result? If the ratio is 1:N, how do you want the answer?
– Woss
I need you to show only 1 time the Itemid Account is not relevant to my query.
– Eduardo Duude
What the
distinct
has to do with more than 100 fields? If the Itemid field is not relevant, just make aselect distinct conta
– maiconfriedel
If the field is not relevant why you included it in the query?
– anonimo
I need all fields of all tables A and B, the main point is the account with the other information.. which are various columns.
– Eduardo Duude
We need DDL, sample data and expected results.
– Ilyes