如何通过查询从组内其他表获取数据?

时间:2019-05-23 11:36:24

标签: sql-server

我试图对一个表中具有相似序列号的记录进行分组。而且我还想使用SerialNo。显示其他与表1有关系的表的列记录。

我有一张桌子1:

enter image description here

表2:

enter image description here

我的查询是:

select CIT_SERIALNUMBER, COUNT(CIT_ID)
 as Cases from Table_2 where CIT_SOURCEID like '%E_One%'
 and (CIT_CREATED BETWEEN '2018-01-15'AND '2019-06-15') and CIT_SERIALNUMBER is not null
   group by CIT_SERIALNUMBER
  having COUNT(CIT_ID)>1 order by  min(CIT_CREATED) desc

以下是结果表:

enter image description here

在上面的查询中,我从表_2 中仅获得 CIT_SERIALNUMBER 条记录。但我也想从 Table_1 ComputerName 中获取数据。因此,预期结果是:

enter image description here

注意:可以通过列T1_Serial和CIT_SERIALNUMBER将两个表1和2连接起来。

请帮助我重写sql查询,以达到上述预期效果。

3 个答案:

答案 0 :(得分:0)

如果我正确理解了您的列名,请尝试以下操作:

select CIT_SERIALNUMBER, ComputerName, COUNT(CIT_ID)
 as Cases from Table_2 join Table_1 on Table_2.CIT_SERIALNUMBER=Table_1.Serial where CIT_SOURCEID like '%E_One%'
 and (CIT_CREATED BETWEEN '2018-01-15'AND '2019-06-15') and CIT_SERIALNUMBER is not null
   group by CIT_SERIALNUMBER
  having COUNT(CIT_ID)>1 order by  min(CIT_CREATED) desc

答案 1 :(得分:0)

试试这个-

SELECT A.ComputerName,
CIT_SERIALNUMBER, 
COUNT(CIT_ID) AS Cases
FROM table_1 A
INNER JOIN Table_2 B ON A.Column T1_Serial = CIT_SERIALNUMBER.
WHERE B.CIT_SOURCEID LIKE '%E_One%'
      AND (B.CIT_CREATED BETWEEN '2018-01-15' AND '2019-06-15')
      AND B.CIT_SERIALNUMBER IS NOT NULL
GROUP BY A.ComputerName,B.CIT_SERIALNUMBER
HAVING COUNT(B.CIT_ID) > 1
ORDER BY MIN(B.CIT_CREATED) DESC;

答案 2 :(得分:0)

这看起来很奇怪,但是我有一个解决方案:

  • 我首先从Table_2中选择所有重复的记录
  • 然后我将Table_1与Table_2的结果集结合在一起,以查看两个表中的列
  • 然后我使用另一个选择从上面的结果集中选择数据并按所有记录分组。

以下是查询:

select z.CIT_SERIALNUMBER, z.ComputerName, z.Cases from (
SELECT y.CIT_SERIALNUMBER, x.ComputerName, y.Cases
    FROM Table_1 x
    right JOIN (
      select CIT_SERIALNUMBER, COUNT(CIT_ID)
 as Cases from Table_2 where CIT_SOURCEID like '%E_One%'
 and (CIT_CREATED BETWEEN '2018-01-15'AND '2019-06-15') and CIT_SERIALNUMBER is not null
   group by CIT_SERIALNUMBER
  having COUNT(CIT_ID)>1 
  ) y ON y.CIT_SERIALNUMBER = x.SerialNo) z  group by CIT_SERIALNUMBER, z.ComputerName, z.Cases

结果集:

enter image description here