gpt4 book ai didi

sql - 仅当至少一行匹配条件时才选择

转载 作者:行者123 更新时间:2023-12-05 00:13:02 25 4
gpt4 key购买 nike

我有一个 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 天时

最佳答案

我也不确定,你期望什么,但是怎么样:

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 将有一行或零行,具体取决于是否满足条件 - 它会连接到其他表中的每一行。

关于sql - 仅当至少一行匹配条件时才选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12481834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com