如何根据状态编写过滤国家/地区的 sql 查询
Posted
技术标签:
【中文标题】如何根据状态编写过滤国家/地区的 sql 查询【英文标题】:How to write sql query for FIlter country as status wise 【发布时间】:2017-04-25 04:48:37 【问题描述】:这里有一张简单的桌子。我想最终得到一张像给定的桌子。编写 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
【问题讨论】:
从 MemberFirms INNER JOIN Status On MemberFirms.StatusId =Status.ID 中选择 MemberFirms.ID,MemberFirms.Name,Status.Name 作为状态 也许您应该添加更多数据,以便我们了解例如 10 个国家/地区的情况。 这是一个过程,我在这里创建了一个简单的国家/地区列表 您的输出格式不是通常要求的格式。这 3 个国家/地区之间的关系是什么,以至于它们都出现在您的输出中的同一行? 这里我只有 2 个表 table1 和 table2 table2 包含状态 【参考方案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
此查询的输出:
【讨论】:
【参考方案2】:试试这个:-
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;
【讨论】:
【参考方案3】:这是给定数据的答案:
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
【讨论】:
【参考方案4】:select Name,Status from Table1 natural join Table2;
这很简单。结果现在应该是这样的。我认为这是我们实际从多个表中检索信息的常用方法。
Name Status
Australia Pending
UAE Submit
India In-Progress
请考虑
【讨论】:
以上是关于如何根据状态编写过滤国家/地区的 sql 查询的主要内容,如果未能解决你的问题,请参考以下文章
编写一个 SQL 查询来判断过去 6 个月中按国家/地区分组的最大销售额是一年中的哪一周?