这里我有一个简单的表格。我想最终得到一张像给定的那样的桌子。编写sql语句来实现此目的的最佳方法是什么?
表1
Id Name Approved
1 Australia 3
2 UAE 1
3 India 2
表2
Id Status
1 Submit
2 In-Progress
3 Pending
将结果显示为
Submitted In-Progress Pending
UAE India Australia
答案 0 :(得分:1)
请尝试以下查询:
create table #country
(
ID int identity(1,1),
Name varchar(30),
Approved int
)
create table #status
(
ID int,
Status varchar(30)
)
insert into #country (Name, Approved) values ('Australia',3), ('UAE',1), ('India',2)
insert into #status (ID, Status) values (1,'Submit'), (2, 'In-Progress'), (3,'Pending')
select Submit, [In-Progress],[Pending]
from (
select t1.Name, t2.Status
from #country t1
inner join #status t2 on t1.Approved = t2.ID
)dd1
pivot (
max(Name) for Status in ([Submit], [In-Progress],[Pending])
) piv
drop table #country
drop table #status
答案 1 :(得分:0)
试试这个: -
select
trim(replace(group_concat(submitted),',',' ')) as submitted,
trim(replace(group_concat(InProgress),',',' ')) as InProgress,
trim(replace(group_concat(Pending),',',' ')) as Pending
from
(
Select
case when status='Submit' then A.Name else ' ' end as submitted,
case when status='In-Progress' then A.Name else ' ' end as InProgress,
case when status='Pending' then A.Name else ' ' end as Pending
FROM
TABLE1 A
INNER JOIN
TABLE2 B
ON A.ID=B.ID
) a;
答案 2 :(得分:0)
以下是给定数据的答案:
select `Submit`,`In-Progress`,`Pending` from
(select `Submit`,`In-Progress`,INP.id from
(select Name as 'Submit',a.id from
(select * from table1)as a
LEFT JOIN
(select * from table2) as b
on a.Approvide = b.`Id`
where b.`STATUS` = 'Submit') as Sub
INNER JOIN
(select Name as 'In-Progress',a.id from
(select * from table1)as a
LEFT JOIN
(select * from table2) as b
on a.Approvide = b.`Id`
where b.`STATUS` = 'In-Progress') as INP
on Sub.id != INP.id) as c
INNER JOIN
(select Name as Pending,a.id from
(select * from table1)as a
LEFT JOIN
(select * from table2) as b
on a.Approvide = b.`Id`
where b.`STATUS` = 'Pending') as Pen
on c.id != Pen.id
答案 3 :(得分:0)
select Name,Status from Table1 natural join Table2;
这很简单。结果应该现在看起来像这样。我认为这是我们如何从多个表中实际检索信息的常用方法。
Name Status
Australia Pending
UAE Submit
India In-Progress
请考虑