SQL - 选择一列比同一日期的其他列大的行

时间:2013-06-21 09:16:32

标签: sql sql-server

说我有一张表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中选择同一small_value large_value大于date的行。因此,对于上面的示例,查询应返回自6以来的最后两行,(field_id = 1 == small_value)> 4field_id = 2 == large_value)。

数据库是Microsoft SQL Server 2012。

感谢您的帮助

5 个答案:

答案 0 :(得分:8)

这样的东西
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 Fiddle DEMO

这是另一个可能的例子

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 Fiddle DEMO

答案 1 :(得分: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 here

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

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 here

答案 2 :(得分: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
    )

答案 3 :(得分: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 Demo

答案 4 :(得分:0)

这样就可以了。请注意,我已从答案中省略了字段表,因为我不需要对WHERE条件使用 fields.code ,而是可以使用 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;