SQL 1行两次
我有一个SQL表,它看起来像:SQL 1行两次,sql,Sql,我有一个SQL表,它看起来像: +----------+-----------+ | ID | Direction | +----------+-----------+ | 1 | left | | 1 | null | | 2 | left | | 2 | null | | 3 | null | | 4 | left | |
+----------+-----------+
| ID | Direction |
+----------+-----------+
| 1 | left |
| 1 | null |
| 2 | left |
| 2 | null |
| 3 | null |
| 4 | left |
| 4 | null |
| 5 | null |
+----------+-----------+
我只想显示每个值一次:
如果将有方向为空且为左的ID 1,则仅显示方向为左的ID 1。
如果ID 1只有空值,则用空值显示它。
使用通用表表达式cte:
with cte as
(
Your huge select...
)
select *
from cte t1
where t1.Direction = 'left'
or not exists (select * from cte t2
where t2.kanbanid = t1.kanbanid
and t2.Direction = 'left')
也就是说,如果您的选择对kanbanid具有“左”方向,则返回该行。如果同一个kanbanid完全没有方向“左”,也返回该行。使用公共表表达式cte:
with cte as
(
Your huge select...
)
select *
from cte t1
where t1.Direction = 'left'
or not exists (select * from cte t2
where t2.kanbanid = t1.kanbanid
and t2.Direction = 'left')
也就是说,如果您的选择对kanbanid具有“左”方向,则返回该行。如果同一个kanbanid完全没有方向“左”,也返回该行。选择distinct*,
按id排序的分区上的行数,方向与任何表中的行1相同
从您的\u表\u名称
从任意_表中选择*
其中,行1=1选择distinct*,
按id排序的分区上的行数,方向与任何表中的行1相同
从您的\u表\u名称
从任意_表中选择*
其中row1=1为什么下面的查询不起作用:
select id,max(dir)
from #temp
group by id
以下是测试数据:
create table #temp
(
id int,
dir char(10)
)
insert into #temp
select 1,'left'
union all
select 1,null
union all
select 2,null
union all
select 3,'right'
union all
select 3,null
union all
select 3,null
select id,max(dir)
from #temp
group by id
聚合函数将忽略null,下面是输出:
为什么下面的查询不起作用:
select id,max(dir)
from #temp
group by id
以下是测试数据:
create table #temp
(
id int,
dir char(10)
)
insert into #temp
select 1,'left'
union all
select 1,null
union all
select 2,null
union all
select 3,'right'
union all
select 3,null
union all
select 3,null
select id,max(dir)
from #temp
group by id
聚合函数将忽略null,下面是输出:
方向可以采用任何其他值吗?不,只有左值或空值。问题中包含外部图像,因为它显示有用的信息。方向可以采用任何其他值吗?不,只有左值或空值。问题中包含外部图像,因为它显示有用的信息。仍然有左值和空值:是。。。桌子有问题吗?我的身份证来自不同的表而非方向。是否涉及两个表???请向我们展示所有涉及的表格,以及一些样本表格数据。这要复杂得多。过一会儿就会回来。我得到了这个错误:希望我用对了。仍然有两个值左和空:是。。。桌子有问题吗?我的身份证来自不同的表而非方向。是否涉及两个表???请向我们展示所有涉及的表格,以及一些样本表格数据。这要复杂得多。过一会儿就会回来。我得到了这个错误:希望我用对了。我的防火墙阻止了图像,所以我看不到输出。但是根据描述,如果它的值不是null,如果它只有null,则需要一个值。然后show nullWas将发布相同的答案。但是对于SQL来说,谈论使用的特定数据库几乎是强制性的。同样的解决方案在SQLite上也适用于我。看起来你的数据库也工作得很好。我的防火墙阻止了图像,所以我看不到输出。但是根据描述,如果它的值不是null,如果它只有null,那么你需要一个值。然后show nullWas将发布相同的答案。但是对于SQL来说,谈论使用的特定数据库几乎是强制性的。同样的解决方案在SQLite上也适用于我。看起来你的数据库也工作得很好。