我正在寻找一种根据标准选择ID(PersonID)的方法。如果此personID不符合标准,我需要选择另一个。为了使它可视化我有两个表: 1。
ID Company LatestOrder
50593 TEST 1
10955 TEST 2
2
ID Criteria_A Criteria_B
50593 1 0
10955 0 0
我需要从``table1 SELECT ID
找到latestOrder = 1
的方法检查此人是否符合表2中的条件(对于任何标准A或B,值为1),如果是,则选择来自table1的ID,其中latestOrder = 2。
只要table1.lastorder>检查标准。 0
有意义吗?我已经陷入了CASE和IIF,CTA的困境,但我似乎无法找到工作方式。我希望有人能够发一些光,我应该去哪个功能方向。
非常感谢任何帮助人员!这是第3版:(
这是我到目前为止的地方:
WITH LastOrdered AS
(
SELECT
OrderBillToID AS PersonID
, OrderDate
, OrderBillToCompanyID AS CompanyID
, OrderBillToCompany
, ROW_NUMBER() OVER(PARTITION BY ODE.OrderBilltoCompanyID ORDER BY ODE.OrderDate DESC) AS LatestOrder
FROM dbo.OrderDetails ODE
INNER JOIN dbo.Persons PER ON ODE.OrderBillToID = PER.ID AND PER.Segment = 'B' AND ODE.OrderBillToCompanyID IS NOT NULL
)
第二次尝试
SELECT
PER.ID
, PER.Company
, LatestOrder
, CASE WHEN PER.ExcludeAll = 0 AND (PER.Age > 17 OR PER.Age = 0) AND PER.DateOfDeath = '1900-01-01' AND PER.TLC = 'NA' AND PER.BulkAskExclude = 0 AND PER.EmailExclude = 0 THEN LastOrder
....here is when I realised that this case won't work.....
FROM dbo.Persons PER
INNER JOIN LastOrdered LO ON LO.PersonID = PER.ID
EXPECTED输出将是:
ID Company
10955 TEST
...
答案 0 :(得分:2)
基本上,您希望订购的最后一个人但不满足Table2
中的任何条件:
SELECT TOP 1
id, Company
FROM Table1
WHERE
id NOT IN(
SELECT id
FROM Table2
WHERE
Criteria_A = 1
OR Criteria_B = 1
)
ORDER BY LatestOrder DESC