T SQL查询查找记录

时间:2017-11-08 21:54:10

标签: sql sql-server tsql sql-server-2012

我有一张类似于此的表

ID   TestID   AdddressID Value  TestDate    Case   Investigation 
1      12        140      15    11/7/2005   Open     Open
1      13        140      19    10/9/2005   Open     Open

如果ID有两个地址ID记录,我希望它显示为

ID   AdddressID  Status 
1      140      New S&A 

我的报告不应该显示我是否再次获得相同的地址3或更多

但如果我将来获得新的地址ID 155,我想要最新的记录和我的报告

ID    AdddressID  Status 
1       155      New A

同样,如果我再次获得地址ID 140(155之后),我不希望ID显示

ID   TestID   AdddressID     Status
 1      12       140          
 1      13       140           New S&A
 1      14       155           New A
 1      15       140          Don't select this record

2 个答案:

答案 0 :(得分:1)

这种缝很简单。

-- sample data
if object_id('tempdb..#yourtable') is not null drop table #yourtable;
create table #yourtable
(
  ID int,
  TestId int,
  AddressID int,
  [Value] int,
  TestDate date,
  [Case] varchar(20),
  Investigation varchar(20)
);
insert #yourtable values
(1, 12, 140, 15, '11/7/2005','Open','Open'),
(1, 13, 140, 19, '10/9/2005','Open','Open'),
(1, 14, 155, 19, '10/9/2005','Open','Open');

-- solution
SELECT
  ID,
  AddressID,
  [Status] = CASE COUNT(*) WHEN 1 THEN 'New A' WHEN 2 THEN 'New S&A ' END
FROM #yourtable
GROUP BY ID, AddressID;

结果

ID          AddressID   Status
----------- ----------- --------
1           140         New S&A 
1           155         New A

答案 1 :(得分:0)

听起来这就是你想要的:

SELECT ID, AddressID, CASE WHEN COUNT(1) = 1 THEN 'New A'
                           ELSE 'New S&A'
                      END as [Status]
FROM YourTable
GROUP BY ID, AddressID
HAVING COUNT(1) < 3

这只会显示少于3次的ID,地址组合:

  

我的报告不应该显示我是否再次获得相同的地址3或更多

如果您想查看这些内容,请移除HAVING...

编辑:如果您只想查看最新的地址更改,请在子查询中使用MAX(),以确保您只能看到每个ID的最新地址ID

SELECT a.ID, a.AddressID, CASE WHEN COUNT(1) = 1 THEN 'New A'
                               ELSE 'New S&A'
                          END as [Status]
FROM YourTable a
JOIN (SELECT MAX(AddressID) AddressID, ID 
      FROM YourTable  
      GROUP BY ID) b ON a.ID = b.ID AND a.AddressID = b.AddressID
GROUP BY a.ID, a.AddressID
HAVING COUNT(1) < 3