仅在至少一行符合条件时选择

时间:2012-09-18 17:12:19

标签: sql sql-server

我有一个select语句,并且只有当其中至少有一个日期与今天有60天的差异时才想返回所有值。 问题是我有一个外部申请,它返回我想要比较的列,它们来自不同的表(一个属于现金项目,另一个属于卡片项目)。
考虑到我有以下内容:

OUTER APPLY (
    SELECT COUNT(*) AS quantity, MIN(date) AS item_date
        FROM dbo.get_cash_items(loans.id_cash) AS cash_item
        HAVING loans.id_product_type = 1 --Cash
    UNION
    SELECT COUNT(*) AS quantity, MIN(date) AS item_date
        FROM dbo.get_card_items(loans.id_card) AS card_item
        HAVING loans.id_product_type = 2 --Card
) AS items

我想仅在DATEDIFF(DAY, MIN(items.item_date), GETDATE()) >= 60时返回所有行,但即使只有一个符合此条件,我也希望它们全部。 这样做的最佳方法是什么?

修改
为了更清楚,我将解释用例:
我需要显示每笔贷款的项目,只有当客户在截止日期超过60天时才会延迟

3 个答案:

答案 0 :(得分:1)

我也不确定,你对此有何看法,但那是怎么回事:

WITH items
     AS (SELECT Count(*)  AS quantity,
                Min(date) AS item_date
         FROM   dbo.Get_cash_items(loans.id_cash) AS cash_item
         HAVING loans.id_product_type = 1
         UNION
         SELECT Count(*)  AS quantity,
                Min(date) AS item_date
         FROM   dbo.Get_card_items(loans.id_card) AS card_item
         HAVING loans.id_product_type = 2)
SELECT a.*
FROM   items AS a,
       (SELECT TOP 1 *
        FROM   items AS b
        WHERE  Datediff(day, b.item_date, Getdate()) >= 60) AS c  

这是一种CROSS JOIN,其中表C将有一行或零行,具体取决于满足条件 - 它将连接到其他表中的每一行。

答案 1 :(得分:0)

你尝试过这样的事吗?

SELECT a.quantity, a.item_date
FROM
    (SELECT COUNT(*) AS quantity, MIN(date) AS item_date
        FROM dbo.get_cash_items(loans.id_cash) AS cash_item
        HAVING loans.id_product_type = 1
    UNION
    SELECT COUNT(*) AS quantity, MIN(date) AS item_date
        FROM dbo.get_card_items(loans.id_card) AS card_item
        HAVING loans.id_product_type = 2) a 
WHERE DATEDIFF(day, a.item_date, GETDATE()) >= 60

答案 2 :(得分:0)

通常我使用CTE来选择我想要选择的记录的密钥然后加入。以下是一个例子的尝试:

with LateClients as
(
    SELECT LoadId FROM Payment Where /*payment date later than 60 days*/
)

SELECT     p.LoanId, 
           p.UserId 
FROM       Payment as p
INNER JOIN LateClients as LC
ON         p.LoanId = lc.LoanId 
OrderBy    p.LoanId, p.UserId

我知道它与你发布的代码有点不同,但这是一个简单的例子,可以解释这个概念。祝你好运!