在单个单元格中显示多个选择

时间:2017-05-01 04:15:47

标签: sql mysqli

请帮我解决以下问题。

考虑我在数据库中有两个表

1.employee 2.Details 

员工表数据将

eid ename  level
 1     x    9th
 2     y    10th

在地址表中数据将是

 AId eid location Adreess_type
 1    1    india    permananet 
 2    1    US        Temporary
 3    2    Japan      permananet 
 4    2    China      Temporary

我需要以下格式输出

eid    ename       fulllocation 
1       X           INDIA -US  
2       y           Japan-CHINA 

5 个答案:

答案 0 :(得分:0)

试试这个:

SELECT 
    e.eid, 
    e.name, 
    GROUP_CONCAT(a.location SEPARATOR  '-') AS fulllocation

FROM 
    employee as e

    INNER JOIN address as a
        ON e.eid = a.eid

GROUP BY 
    e.eid

答案 1 :(得分:0)

select employee.eid, employee.ename, t.fulllocation
from employee
inner join (select  eid, group_concat(location SEPARATOR  '-') as fulllocation from Address group by eid) t
on employee.eid = t.eid

考虑GROUP_CONCAT有一些限制,这是什么以及如何改变(如果需要)呢?请查看相关文档。

答案 2 :(得分:0)

DECLARE @t1 TABLE
(
    eid int NOT NULL, 
    ename varchar(50),
    level varchar(50)
)

DECLARE @t2 TABLE
(
    aid int NOT NULL,
    eid int, 
    location varchar(50),
    address_type varchar(50)
)

INSERT INTO @t1 SELECT 1, 'x', '9th'
INSERT INTO @t1 SELECT 2, 'y', '10th'

INSERT INTO @t2 SELECT 1, 1, 'india', 'permanent'
INSERT INTO @t2 SELECT 2, 1, 'US', 'temporary'
INSERT INTO @t2 SELECT 3, 2, 'Japan', 'permanent'
INSERT INTO @t2 SELECT 4, 2, 'China', 'temporary'

SELECT * FROM @t1
SELECT * FROM @t2

SELECT t1.eid, t1.ename, t2.fullLocation
FROM @t1 AS t1
INNER JOIN (
    SELECT eid, COUNT(*) AS noofrecs
        , fullLocation = LTRIM(RTRIM(ISNULL(STUFF(
                    (
                        SELECT DISTINCT '-' + CAST(t2.location as nvarchar(max))
                        FROM @t2 t2
                        WHERE t1.eid = t2.eid
                        FOR XML PATH (''), TYPE).value('.', 'nvarchar(max)'
                    ), 1, 1, ''), '')))

    FROM @t2 as t1
    GROUP BY eid
) AS t2
ON t1.eid = t2.eid

答案 3 :(得分:0)

DECLARE @t1 TABLE
(
    eid int NOT NULL, 
    ename varchar(50),
    level varchar(50)
)

DECLARE @t2 TABLE
(
    aid int NOT NULL,
    eid int, 
    location varchar(50),
    address_type varchar(50)
)

INSERT INTO @t1 SELECT 1, 'x', '9th'
INSERT INTO @t1 SELECT 2, 'y', '10th'

INSERT INTO @t2 SELECT 1, 1, 'india', 'permanent'
INSERT INTO @t2 SELECT 2, 1, 'US', 'temporary'
INSERT INTO @t2 SELECT 3, 2, 'Japan', 'permanent'
INSERT INTO @t2 SELECT 4, 2, 'China', 'temporary'

SELECT * FROM @t1
SELECT * FROM @t2

SELECT b.eid,b.ename
, STUFF((SELECT '_ ' + a.location FROM @t2 A
Where A.eid=B.eid FOR XML PATH('')),1,1,'') As fulllocation
From @t1 B
Group By b.eid,b.ename

答案 4 :(得分:0)

为了保留位置的顺序,您可以继续

SELECT
  e.eid
  , e.ename
  , CONCAT_WS('-', p.location, t.location) AS fulllocation
FROM Employee e
JOIN Address p
  ON e.eid = p.eid
  AND p.address_type = 'permananet'
JOIN Address t
  ON e.eid = t.eid
  AND t.address_type = 'Temporary'
;

查看实际操作:SQL Fiddle

请评论是否需要调整/进一步详细说明。