2

假设我有一张桌子,values看起来像:

id|field_id|value|date
1 |1       |2    |2013-06-01
2 |2       |5    |2013-06-01
3 |1       |3    |2013-06-02
4 |2       |9    |2013-06-02
5 |1       |6    |2013-06-03
6 |2       |4    |2013-06-03

还有一张桌子,fields,看起来像

id|code
1 |small_value
2 |large_value

我想选择大于相同的values行。因此,对于上面的示例,查询应该从 since , ( = == ) > ( = == )返回最后两行。small_valuelarge_valuedate6field_id1small_value4field_id2large_value

数据库是 Microsoft SQL Server 2012。

谢谢你的帮助

4

5 回答 5

9

像这样的东西怎么样

SELECT * 
FROM [values] v
WHERE EXISTS(
  SELECT 1
  FROM [values] vl
  WHERE vl.FIELD_ID = 2
  AND vl.date = v.date
  AND vl.value < v.value
 )
AND v.FIELD_ID = 1

SQL 小提琴演示

这是另一个可能的例子

SELECT *
FROM [values] vs INNER JOIN
    [values] vl ON vs.date = vl.date AND vs.FIELD_ID = 1 AND vl.FIELD_ID = 2 
WHERE vs.value > vl.value

SQL 小提琴演示

于 2013-06-21T09:25:11.180 回答
1

单程:

select [date],
       max(case field_id when 1 then [value] end) small_value,
       max(case field_id when 2 then [value] end) large_value
from [values]
group by [date]
having max(case field_id when 1 then [value] end) > 
       max(case field_id when 2 then [value] end)

SQLFiddle在这里

或者,要将记录视为单独的行,请尝试:

select v1.*
from [values] v1
join [values] v2 
  on v1.[date] = v2.[date] and 
     v1.field_id = 3-v2.field_id and
     case v1.field_id when 1 then v1.[value] else v2.[value] end >
     case v1.field_id when 2 then v1.[value] else v2.[value] end

SQLFiddle在这里

于 2013-06-21T09:28:00.907 回答
1

像这样,还是我错过了什么?:

    declare @tmp table (
     id int,
     field_id int,
     value int,
     [date] datetime
    )

    select * from @tmp
    where [date] in (
        select distinct t.[date]
        from @tmp t
        left join (select * from @tmp) as s on s.[Date] = t.[Date]
          and s.field_id = 1
        left join (select * from @tmp) as l on l.[Date] = t.[Date]
          and l.field_id = 2
         where s.value > l.value
    )
于 2013-06-21T09:31:04.840 回答
1
SELECT 
  small.[Date]
, small.ID as SmallID
, small.Value as SmallValue
, large.ID as LargeID
, large.Value as LargeValue
FROM [values] small
INNER JOIN [values] large ON small.[Date] = large.[Date] AND small.field_id =1 AND large.field_id =2
WHERE small.Value > large.Value

SQLFiddle 演示

于 2013-06-21T09:31:42.743 回答
0

这可以解决问题。请注意,我从答案中省略了字段表,因为我不需要将fields.code用于 WHERE 条件,但可以使用fields.id代替。这与值表中的field_id相同。

SELECT V.id, V.field_id, V.value, V.date
FROM [values] AS V 
  INNER JOIN [values] AS V1 
    ON V.date = V1.date
WHERE (((V.field_id)=1) AND ((V.value)>[V1].[value]) AND ((V1.field_id)=2)) 
   OR (((V.field_id)=2) AND ((V.value)<[V1].[value]) AND ((V1.field_id)=1))
ORDER BY V.id;

或者,如果您想要一行中的所有信息:

SELECT V.id, V.field_id, V.value, V1.id, V1.field_id, V1.value, V.date
FROM [values] AS V INNER JOIN [values] AS V1 ON V.date = V1.date
WHERE (((V.field_id)=1) AND ((V.value)>[V1].[value]) AND ((V1.field_id)=2))
ORDER BY V.id;
于 2013-06-21T09:56:38.257 回答