最小ID按另一个表中的列分组

时间:2017-01-13 21:13:52

标签: sql group-by min

我认为这是非常简单的,但是我无法使用分区或分组来使其工作。我需要获得两个昏暗键中的较低者,但是我仍然需要抓住领域昏暗键,因为我在该子查询之外的查询的另一部分中使用它。

    SELECT 
ac.ACCOUNT_DIM_KEY,
iid.CUST_ID,
ter.TERRITORY_DIM_KEY,
ROW_NUMBER() OVER (PARTITION BY iid.CUST_ID ORDER BY ac.ACCOUNT_DIM_KEY) AS MIN_ACCT_KEY
FROM   DEXODS.OPUB_MDM_CCV_ID iid,
       DEXWHS.D_ACCOUNT_VEEVA ac,
       DEXWHS.D_TERRITORY ter
WHERE  ac.IMS_ID = iid.VAL_1_ID
AND    SUBSTR(ac.PRIMARY_TERRITORY, 1, 8) = ter.TERRITORY_CODE
AND    ac.ACTIVE_FLAG = 'Y' 
AND    iid.SCNDY_ID_TYP_XID = 202325 
AND    iid.cust_id = '53050249'
AND    MIN_ACCT_KEY= 1

我想要的结果是只返回帐户昏暗键307070 ACCOUNT_DIM_KEY CUST_ID TERRITORY_DIM_KEY MIN_ACCT_KEY 307070 53050249 -3 1
2565820 53050249 43 2

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

这样做你想要的吗?

// get the TestServiceImpl.java service component
TestServiceImpl testService = getSlingScriptHelper().getService(TestServiceImpl.class);

//com.adobe.cq.sightly.WCMUsePojo.getSlingScriptHelper()

注意:SELECT ac.ACCOUNT_DIM_KEY AS ACCOUNT_DIM_KEY, iid.CUST_ID ter.TERRITORY_DIM_KEY FROM DEXODS.OPUB_MDM_CCV_ID iid JOIN DEXWHS.D_ACCOUNT_VEEVA ac ON ac.IMS_ID = iid.VAL_1_ID JOIN DEXWHS.D_TERRITORY ter ON substr(ac.PRIMARY_TERRITORY, 1, 8) = ter.TERRITORY_CODE WHERE ac.ACTIVE_FLAG = 'Y' AND iid.SCNDY_ID_TYP_XID = 202325 AND iid.cust_id = '53050249' ORDER BY ac.ACCOUNT_DIM_KEY FETCH FIRST 1 ROW ONLY; 是ANSI标准SQL。在某些数据库中,拼写为FETCH FIRST 1 ROW ONLYLIMIT,甚至更加神秘。

答案 1 :(得分:0)

;WITH cte AS (
    SELECT 
       ac.ACCOUNT_DIM_KEY,
       iid.CUST_ID,
       ter.TERRITORY_DIM_KEY,
       ROW_NUMBER() OVER (PARTITION BY iid.CUST_ID ORDER BY ac.ACCOUNT_DIM_KEY) AS MIN_ACCT_KEY
    FROM
       DEXODS.OPUB_MDM_CCV_ID iid
       INNER JOIN DEXWHS.D_ACCOUNT_VEEVA ac
       ON ac.IMS_ID = iid.VAL_1_ID
       AND ac.ACTIVE_FLAG = 'Y'
       INNER JOIN DEXWHS.D_TERRITORY ter
       ON SUBSTR(ac.PRIMARY_TERRITORY, 1, 8) = ter.TERRITORY_CODE
WHERE
    iid.SCNDY_ID_TYP_XID = 202325 
    AND    iid.cust_id = '53050249'
)

SELECT *
FROM
    cte
WHERE
    MIN_ACCT_KEY= 1

根据您在此处所写的内容,可以为任意数量的客户执行此操作,只需删除iid.cust_id = '53050249'即可为每位客户获取正确的行。请注意,这是使用显式连接而不是隐式连接语法。更新后唯一的错误是尝试在where语句中引用ROW_NUMBER()的列别名。如果不将原始查询作为派生表或公用表表达式包装,则该别名和列将不可用。我已经展示了公用表表达方法。