选择符合条件的所有记录以及与条件不匹配的下一条记录

时间:2015-05-11 18:54:36

标签: sql ms-access

我有一个包含这样的列的表:

ID, Description, PC, Account, Amount

我将在" PC"中寻找009值。列,每个数据在" ID"中有一个顺序编号的唯一ID。柱。每个数据都带有009" PC"价值将至少有一个跟随它的项目没有" 009"作为PC值。

有什么方法可以编写一个真实且与下面的假代码相似的查询?这样的事情真的可能吗?

SELECT  
table.ID AS ID,  
table.Description AS Description,  
table.PC AS PC
WHERE ((table.PC = 009) OR (whatever, as long as table.ID-1's "PC" value = 009))

3 个答案:

答案 0 :(得分:0)

如果您知道id是真正顺序的,您可以将逻辑放在WHERE子句中:

SELECT t.ID, t.Description, t.PC AS PC
FROM table as t
WHERE t.PC = 009 OR
      EXISTS (SELECT 1
              FROM table as t2
              WHERE t2.id = t.id - 1 AND t2.PC = 009
             )
ORDER BY t.ID;

答案 1 :(得分:0)

SELECT  
table.ID AS ID,  
table.Description AS Description,  
table.PC AS PC
FROM table
WHERE ((table.PC = '009') OR 
table.ID - 1 = 
  (
  SELECT table.ID
  FROM table
  WHERE table.PC = '009'
  )
)

答案 2 :(得分:0)

users = users.Where(m => m.FirstName.Contains(query) || m.LastName.Contains(query) || (m.FirstName + " " + m.LastName).Contains(query) || (m.LastName + " " + m.FirstName).Contains(query) || (m.LastName + ", " + m.FirstName).Contains(query));