[英]How to get Email ID(one value) for each ID for 1st table and then display Email Name from 2nd table as comma Separated in SQL Server 2012?
我嘗試過的 結果想要這樣的結果從一個表開始,對於每個ID,根據某些條件,可以有多個電子郵件ID,例如
ID EmailID's
1 Mike.Foster@Mail.com
1 lilly.Foster@Mail.com
2 Michel.Josh@Mail.com
2 Nash.Ted@Mail.com
我必須從另一個表中的這些ID中獲取電子郵件名稱,就像這樣
我需要的輸出
Email_Name
Foster.Mike,Foster.Lilly
Josh.Michel,Ted.Nash
這就是我嘗試過的。
SELECT User_Email =
STUFF((SELECT DISTINCT ', ' + User_Email
FROM table1 b
WHERE b.Component_ID= a.Component_ID
and [Role] ='Team Lead' and Functional_Group ='Product'
FOR XML PATH('')), 1, 2, '')
FROM [WFS].table1 a
GROUP BY table1
現在我要另一個表電子郵件名稱
Select EmailNamefrom Table2 where EmailIDs IN ( 'code for Email')
表1模式
ID Component_ID EmailIDs Role Functional_Group
1 1 Mike.Foster@Mail.com Team Lead Product
2 1 lilly.Foster@Mail.com Team Lead Product
3 2 Michel.Josh@Mail.com Team Lead Product
4 2 Nash.Ted@Mail.com Team Lead Product
表2模式
ID EmailIDs EmailName
1 Mike.Foster@Mail.com Foster.Mike
2 lilly.Foster@Mail.com Foster.Lilly
歡迎任何建議。謝謝
您實際上已經關閉,但是您的SQL與您的架構不匹配。 這是您想要的作品:
SELECT Email_Name =
STUFF((SELECT DISTINCT ', ' + EmailIDs
FROM table1 b
WHERE b.Component_ID= a.Component_ID
and [Role] ='Team Lead' and Functional_Group ='Product'
FOR XML PATH('')), 1, 2, '')
FROM table1 a
GROUP BY a.Component_ID;
編輯:我不明白你到底在問什么。 可能這就是您的意思嗎?
SELECT STUFF((SELECT ', ' + EmailName
FROM Table2 where EmailIDs IN ( SELECT EmailIDs
FROM table1
WHERE [Role] ='Team Lead' and Functional_Group ='Product')
FOR XML PATH('')), 1, 2, '')
或者你的意思是這樣的:
SELECT DISTINCT Component_ID, emailNames
FROM table1
CROSS APPLY (SELECT STUFF((SELECT ', '+t2.EmailName
FROM table2 t2
INNER JOIN TABLE1 t1 ON t1.EmailIDs = t2.EmailIDs
WHERE t1.Component_ID = Table1.Component_ID
FOR XML PATH('')), 1, 2, '')
) t(EmailNames)
WHERE [Role] ='Team Lead' and Functional_Group ='Product'
當我發現GROUP_CONCAT()
是MySQL特定的函數時 ,請忽略此答案 ,這意味着它在SQL Server中將不起作用,但是,我將其留作以后參考。
SELECT
GROUP_CONCAT(EmailName SEPARATOR ', ') as name
FROM
table1
INNER JOIN table2 ON table1.EmailIDs=table2.EmailIDs
WHERE
table1.EmailIDs=table2.EmailIDs
GROUP BY
table1.Component_ID
輸出:
福斯特·邁克,福斯特·莉莉
泰德·納什,喬什·米歇爾
工作的SQL小提琴
文件: https : //dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat
您需要使用STUFF()
CTE
:
WITH t AS (
SELECT t1.*, t2.emailname
FROM table1 t1 INNER JOIN
table2 t2
ON t2.emailids = t1.emailids
)
SELECT id, STUFF ( (SELECT DISTINCT ','+t1.emailname
FROM t t1
WHERE t1.id = t.id
FOR XML PATH ('')
), 1, 1, ''
) AS Email_Name
FROM t
GROUP BY id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.