我正在构建一个使用子查询的查询。当子查询返回一个值我要返回该值时,如果子查询返回任何我想要返回今天的日期。问题是,当子查询有一个值时,我不知道如何引用我想要返回的列。在这种情况下,effDate:
SELECT
CASE WHEN exists(SELECT TOP 1 pp.Period_End_Date [effDate]
FROM Employee ee WITH (NOLOCK)
INNER JOIN PayPlanner pp WITH (NOLOCK) ON ee.ClientID = pp.ClientID
AND ee.PaygroupUID = pp.PaygroupUID
WHERE ee.ClientID = 85845
AND pp.ClientID = 85845
AND ee.EmpUID = 133066325953730
AND ee.m_eff_end_date IS NULL
AND pp.m_eff_end_date IS NULL
AND pp.Payroll_Status IN ('E','I')
AND pp.Date_Type IN ('R','A')
ORDER BY Period_End_Date) then ???HOW TO ACCESS effDate HERE???
ELSE GETDATE()
END
答案 0 :(得分:3)
您无法访问这些子查询中的列。您似乎想要最大日期(如果存在)或当前日期。而是使用SELECT COALESCE(MIN(pp.Period_End_Date), GETDATE()) as [effDate]
FROM Employee ee WITH (NOLOCK)
INNER JOIN PayPlanner pp WITH (NOLOCK) ON ee.ClientID = pp.ClientID
AND ee.PaygroupUID = pp.PaygroupUID
WHERE ee.ClientID = 85845
AND pp.ClientID = 85845
AND ee.EmpUID = 133066325953730
AND ee.m_eff_end_date IS NULL
AND pp.m_eff_end_date IS NULL
AND pp.Payroll_Status IN ('E', 'I')
AND pp.Date_Type IN ('R', 'A')
的聚合查询:
MIN()
注意:您的查询似乎需要最短期间结束日期。我实际上期望最大值。但无论如何,聚合函数是@Entity
public class Customer extends BaseEntity {
private String firstname;
private String lastname;
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private Set<Address> addresses;
...
@Entity
public class Address extends BaseEntity {
private String street;
private String houseNumber;
private String zipCode;
private String city;
@ManyToOne
private Customer customer;
...
。
答案 1 :(得分:1)
一种方法是将EXISTS子查询封装在COALESCE中:
SELECT COALESCE(( SELECT TOP 1
pp.Period_End_Date [effDate]
FROM Employee ee WITH ( NOLOCK )
INNER JOIN PayPlanner pp WITH ( NOLOCK ) ON ee.ClientID = pp.ClientID
AND ee.PaygroupUID = pp.PaygroupUID
WHERE ee.ClientID = 85845
AND pp.ClientID = 85845
AND ee.EmpUID = 133066325953730
AND ee.m_eff_end_date IS NULL
AND pp.m_eff_end_date IS NULL
AND pp.Payroll_Status IN ( 'E', 'I' )
AND pp.Date_Type IN ( 'R', 'A' )
ORDER BY Period_End_Date
), GETDATE());