【问题标题】:Match on Multiple Rows in SQL Server在 SQL Server 中匹配多行
【发布时间】:2013-08-27 15:46:21
【问题描述】:

我遇到了一个复杂的 SQL Server 查询,我正试图解决这个问题,遇到了困难,不确定最佳/最快的方法。我有一个良好的开端,但并不顺利。

基本上,我需要创建一个 Select 语句,它将向我发送满足以下要求的 content_ids 列表:

  • 唯一的 content_idfield_id 的 12680 匹配 field_values
  • content_idfield_id 的 12643 没有“是”,但另一行具有相同的 content_idfield_id 12680 与相同的 content_id 匹配,值为“是”
  • 仅在过去 24 小时内带有 create_date 的项目

数据库长这样:

content_id | field_id | field_value                             | create_date
_________________________________________________________________________________________
12         | 12680    | 210b1183c3718142594425ab9538376ebb7f1e0 | 2012-02-21 22:44:51.167
12         | 12643    | Yes                                     | 2012-02-21 22:44:51.167
13         | 12680    | 210b1183c3718142594425ab9538376ebb7f1e0 | 2012-02-21 22:44:51.167
13         | 12643    |                                         | 2012-02-21 22:44:51.167

这是我目前得到的:

SELECT DISTINCT Event1.content_id
FROM tblIVTextData AS Event1
    JOIN tblIVTextData AS Event2
        ON (Event1.content_id != Event2.content_id AND 
            Event1.field_value = Event2.field_value)
    JOIN tblIVTextData AS Event3
        ON(Event3.field_id = 12643 AND
           Event3.field_value = 'Yes' AND
           Event3.content_id = Event1.content_id)
    WHERE Event1.field_id = 12680 AND 
        Event1.create_date > dateadd(hh, -300, getdate())

我在选择第一次出现的“是”与 field_values 匹配时迷失了方向。有关如何完成此或性能改进的任何建议?

【问题讨论】:

  • content_id 必须同时满足前两个条件或其中任何一个条件吗?
  • @amcdni 。 . .此语句没有意义:“content_id 的 field_id 为 12643,没有'Yes',但另一行具有相同的 content_id 但 field_id 12680 匹配此相同的 content_id 的值为 'Yes'”。您能否为您的示例数据提供所需的输出?
  • @GordonLinoff 示例输出如下所示: content_id 13

标签: sql sql-server database select


【解决方案1】:

我不了解您的条件,也不了解示例查询(您说“24”小时作为条件,但在 SQL 中使用“300”小时)。

但是,我认为您可以使用聚合和 having 子句来做您想做的事情。下面是一个使用field_value <> 'Yes' 测试一次出现的 12680 和至少一次出现的 12643 的示例:

select e.ContentId
from tblIVTextData e
where e.create_date > dateadd(hh, -24, getdate())
group by e.ContentId
having sum(case when field_id = 12680 then 1 else 0 end) = 1 and
       sum(case when field_id = 12643 and field_value <> 'Yes' then 1 else 0 end) > 0

【讨论】:

  • 哎呀... 300 是一个错字
【解决方案2】:
with content_cte(content_id,field_id)as
(select distinct content_id,field_id from tblIVTextData where content_id=12643 
and field_value <>'Yes')

SELECT DISTINCT Event1.content_id
FROM 
tblIVTextData AS Event1
JOIN tblIVTextData AS Event2
ON (Event1.content_id != Event2.content_id AND 
Event1.field_value = Event2.field_value)
JOIN content_cte AS Event3
ON(Event3.content_id = Event1.content_id AND Event1.field_value='Yes')
WHERE Event1.field_id = 12680 
Event1.create_date > dateadd(hh, -24, getdate())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 2018-06-15
    • 2011-04-18
    • 1970-01-01
    相关资源
    最近更新 更多