如何在SAP HANA中加入特定的Max行

时间:2017-08-01 19:22:47

标签: sql hana

您好我在SAP HANA中执行查询并尝试仅使用最新项目获取唯一记录(在这种情况下,它是合同开始日期):

我正在运行的查询是:

SELECT 
 A1."ObjectShipToPartyName",
 A1."ObjectShipToParty",
 A1."ObjShippedDate",
 A1."ObjInstalledDate",
 A1."ProductModelNumber",
 A1."RefProd",
 A1."RefProdDescription",
 A1."AssetType",
 A1."IbaseComponentType",
 A1."WarrantyStartDate",
 A1."WarrantyEndDate",
 A1."WarrantyStartDateStatus",
 A1."WarrantyEndDateStatus",
 A1."ValidWarrStartDate",
 A1."ValidWarrEndDate",
 A1."IbaseObjectID",
 A1."AssociatedIBaseID",
 A2."ContractID",
 Max(A2."HDRStartDate") AS "HDRStartDate",
 Max(A2."HDREndDate") AS "HDREndDate",
 A2."ContractType"

FROM "Table1" A1 

LEFT OUTER JOIN "Table2" A2
    ON LTRIM(A2."IBASEID", 0) = LTRIM(A1."AssociatedIBaseID", 0) 

WHERE A1."AssetType" = '01'
    AND Cast(A1."ObjShippedDate" AS Date) > TO_DATE('20070801', 'YYYYMMDD') 
    AND A2."LineStatusText" IN ('Active','Completed')
    AND A2."HDRStatusTxt" IN  ('Active','Completed')
    AND A2."ContractType" <> 'ZQAS'

 GROUP BY
 A1."ObjectShipToPartyName",
 A1."ObjectShipToParty",
 A1."ObjShippedDate",
 A1."ObjInstalledDate",
 A1."ProductModelNumber",
 A1."RefProd",
 A1."RefProdDescription",
 A1."AssetType",
 A1."IbaseComponentType",
 A1."WarrantyStartDate",
 A1."WarrantyEndDate",
 A1."WarrantyStartDateStatus",
 A1."WarrantyEndDateStatus",
 A1."ValidWarrStartDate",
 A1."ValidWarrEndDate",
 A1."IbaseObjectID",
 A1."AssociatedIBaseID",
 A2."ContractID",
 A2."ContractType"

这给出了如下所示的数据: enter image description here

在这里,我只对保持突出显示的行的合同感兴趣。非常感谢任何帮助,我对SQL很新。

1 个答案:

答案 0 :(得分:1)

这是一个常见的要求。根据您的澄清,解决方案可能如下所示:

SELECT 
 A1."ObjectShipToPartyName",
 A1."ObjectShipToParty",
 A1."ObjShippedDate",
 A1."ObjInstalledDate",
 A1."ProductModelNumber",
 A1."RefProd",
 A1."RefProdDescription",
 A1."AssetType",
 A1."IbaseComponentType",
 A1."WarrantyStartDate",
 A1."WarrantyEndDate",
 A1."WarrantyStartDateStatus",
 A1."WarrantyEndDateStatus",
 A1."ValidWarrStartDate",
 A1."ValidWarrEndDate",
 A1."IbaseObjectID",
 A1."AssociatedIBaseID",
 A2."ContractID",
 A2."HDRStartDate"
 A2."HDREndDate"
 A2."ContractType"

FROM 
    "Table1" A1 

    LEFT OUTER JOIN "Table2" A2
    ON LTRIM(A2."IBASEID", 0) = LTRIM(A1."AssociatedIBaseID", 0) 

    inner join
         (SELECT "IBASEID", MAX("HDREndDate") as "MAX_HDREndDate"
          FROM "Table2" 
          WHERE 
                "LineStatusText" IN ('Active','Completed')
            AND "HDRStatusTxt" IN  ('Active','Completed')
            AND "ContractType" !='ZQAS'
          GROUP BY "IBASEID") S2

    on (A2."IBASEID", A2."HDREndDate") = (S2."IBASEID", S2."MAX_HDREndDate")

WHERE 
    A1."AssetType" = '01'
    AND TO_DATE(A1."ObjShippedDate") > TO_DATE('20070801', 'YYYYMMDD');

聚合需要与实际数据收集位于不同的级别。因此,您首先找到每个IBASEID的所有最新/最大日期,然后检索这些记录所需的详细信息 结果集是您加入Table1的内容。

附注:为了便于阅读,我会坚持使用一种类型转换(TO_DATECAST)。加入改造后的IBASEID并不能提高绩效。更好的选择是以正确的格式存储数据。