gpt4 book ai didi

sql-server-2008 - mssql如何通过比较其他字段来检索字段记录?

转载 作者:行者123 更新时间:2023-12-04 06:56:38 24 4
gpt4 key购买 nike

我有一张 table ;让它被称为表1;具有以下字段和数据

msgid  msisdn teaserid send
1 333 1 1
2 333 1 0
3 444 2 1
4 444 2 1
5 444 3 1

我需要一个查询,为每个具有相同 msisdn、teaserid 的记录返回 send = 1 的那些 msgid。在上面的例子中,我想要 msgid: 3,4,5 作为结果。如何使用 mssql 查询完成此操作?

最佳答案

这是 window functions 的可爱用法:

declare @t table (msgid int,msisdn int,teaserid int,send int)
insert into @t (msgid,msisdn,teaserid,send) values
(1,333,1,1),
(2,333,1,0),
(3,444,2,1),
(4,444,2,1),
(5,444,3,1)

select * from (
select *,MIN(send) OVER (PARTITION BY msisdn,teaserid) as all1
from @t
)t
where all1 = 1

结果:

msgid       msisdn      teaserid    send        all1
----------- ----------- ----------- ----------- -----------
3 444 2 1 1
4 444 2 1 1
5 444 3 1 1

通过计算 msisdn,teaserid 分区的 MIN(send),只有当所有 send 值都是1. 如果只有一行有 0,那将是该分区的最小值。

关于sql-server-2008 - mssql如何通过比较其他字段来检索字段记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14516752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com