【问题标题】:Merging the output of two related SQL queries合并两个相关 SQL 查询的输出
【发布时间】:2017-01-13 00:00:30
【问题描述】:

在 SQL Server 中,我有来自两个表的两个查询。

第一个表“Values1”有两列:“index1”和“value1”。第二个表“Values2”包含“index2”和“value2”列。

我想要一个查询,对于一对索引值 'd1' 和 'd2' 可以输出所有 'index1' 和 'value1' 行以及在 'd1' 和 'd2' 之间的对应 index1,以及“Values2”表中的“index2”值在“d1”和作为第一个查询的结果给出的“value1”之间的行数,我希望第二个查询循环第一个查询的结果。所以如果第一个表是:

index1:value1
10:'A'
20:'B'
30:'C'
40:'D'
50:'E'

第二张表是:

index2:value2
0:'F'
5:'G'
15:'H'
25:'I'
35:'J'

对 d1=18 和 d2=32 的查询将导致:

20,B,3
30,C,4

如何结合这两个查询来产生这种结果?

【问题讨论】:

  • 所以您想计算Values2index2 介于18'B' 之间的行数?这有什么意义?
  • 为什么这需要是一个单一的查询?感觉就像您有一个查询可以返回任意数量的行,而另一个查询只返回两个,并且它们彼此没有关系。考虑一下如果第一个表中有 25:'Q' 会发生什么,然后会发生什么?

标签: sql sql-server


【解决方案1】:

你似乎想要:

select t1.index1, t1.value1, count(*)
from t1 join
     t2
     on t2.value2 between @d1 and t1.value1
where t1.value1 between @d1 and @d2
group by t1.index1, t1.value1;

【讨论】:

    【解决方案2】:
    Select  *
    From    (
            Select  index1 as [index],value1 as value
            From    ( Values (10,'A'),(20,'B'),(30,'C'),(40,'D'),(50,'E'))as Temp(index1,value1)
    
            Union
            Select  index2 as [index],value2 as value
            From    ( Values (0,'F'),(5,'G'),(15,'H'),(25,'I'),(35,'J')) as Temp(index2,value2)
            ) D1
    Where   D1.[index] between 18 and 32
    order by [index] 
    

    【讨论】:

      【解决方案3】:

      你的问题有点不清楚。获取values1 记录很简单:

      select * from values1 where index1 between @d1 and @d2;
      

      至于第二部分:您想计算表 values2 中的记录并且与您的解释相矛盾,您似乎只是想计算 index2 <= index1 中的记录。

      select count(*) from values2 where index2 <= @index1
      

      两者结合:

      select
        index1,
        value1,
        (select count(*) from values2 v2 where v2.index2 <= v1.index1) as cnt
      from values1 v1
      where index1 between @d1 and @d2;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-26
        • 1970-01-01
        • 2019-08-05
        • 1970-01-01
        • 1970-01-01
        • 2020-12-23
        • 2017-05-18
        相关资源
        最近更新 更多