首页 > 解决方案 > 如何获取所有查询

问题描述

我有以下代码。我正在尝试从计费中获取 pws_endchargedate 小于今天日期的所有行。这意味着即使帐单中的一个行末收费日期大于今天的日期,它也不会显示。现在我得到的结果包括一些资产,这些资产的账单行的 endchargedate 大于今天的日期。

select distinct billing.pws_AssetIdName
from pws_billingchargeitems billing
join pws_assetservice assetser on billing.pws_AssetId=assetser.pws_AssetId
join pws_asset asset on asset.pws_assetId=billing.pws_AssetId
join Account acc on asset.pws_AccountId=acc.AccountId
where acc.AccountNumber in ('13636','172146','201194','34328','15236')
      and billing.pws_EndChargeDate< getutcDate() and assetser.statuscode=1

标签: sqltsql

解决方案


该查询根本不会执行您希望它执行的操作,因为其中没有任何内容可以处理“如果任何日期大于今天的日期,则不包含数据”规则。

你可以做这样的事情(有很多方法可以做到这一点):

with badAssets AS (
    SELECT DISTINCT
        pws_AssetId
    FROM
        pws_billingchargeitems billing
        join pws_assetservice assetser on billing.pws_AssetId = assetser.pws_AssetId
        join pws_asset asset on asset.pws_assetId = billing.pws_AssetId
        join Account acc on asset.pws_AccountId = acc.AccountId
    WHERE
        acc.AccountNumber in ('13636','172146','201194','34328','15236')
        and assetser.statuscode = 1
        and billing.pws_EndChargeDate > getutcDate())
select distinct 
    billing.pws_AssetIdName
from 
    pws_billingchargeitems billing
    join pws_assetservice assetser on billing.pws_AssetId = assetser.pws_AssetId
    join pws_asset asset on asset.pws_assetId = billing.pws_AssetId
    join Account acc on asset.pws_AccountId = acc.AccountId
where 
    acc.AccountNumber in ('13636','172146','201194','34328','15236')
    and assetser.statuscode = 1
    and NOT EXISTS (SELECT * FROM badAssets WHERE badAssets.AssetId = billing.AssetId);

因此,我们列出了未来有结束收费日期的所有资产,然后我们在原始查询末尾引用此列表,而不是一次只查看一行数据的旧测试(并且没用)。


推荐阅读