2

我正在尝试修改现有查询,该查询显示共享 ID 的重复行,同时具有不同的辅助 ID。

SELECT  IM.*, C.Client, U.Name, R.FrequencyUnit, R.FrequencyDuration, R.RIID
FROM    itemsMisc IM
LEFT JOIN Clients C on C.ClientID = IM.ClientID
LEFT JOIN Users U on U.UserID = IM.UserID
LEFT JOIN Recurringitem R ON (R.ClientID = C.ClientID AND IM.Rate = R.Rate AND IM.Title = R.Title)
WHERE   (IM.CID = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#CID#">) 
  AND   (IM.Invoiced = 0)
ORDER BY IM.DateCompleted ASC;

发生的情况是,如果同一个用户制作了 2 个类似的重复项目,则重复的行显示为具有相同的 IMID(来自 itemsMisc),但具有来自 Recurringitems 的不同 RIID。

我在 IMID 上尝试了 GROUP BY,发现我必须在 GROUP BY 中包含所有选择的项目,这让我无处可去。

SELECT IM.IMID, IM.UserID, IM.ClientID, IM.Rate, IM.Title, IM.CID, IM.QTY, IM.DateCompleted, C.Client, U.Name, R.FrequencyUnit, R.FrequencyDuration, R.RBID
FROM    ItemMisc IM
LEFT JOIN Clients C on C.ClientID = IM.ClientID
LEFT JOIN Users U on U.UserID = IM.UserID
LEFT JOIN Recurringitem R ON (R.ClientID = C.ClientID AND IM.Rate = R.Rate AND IM.Title = R.Title)
WHERE   (IM.CID = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#CID#">) 
  AND   (IM.Invoiced = 0)
GROUP BY IM.IMID, IM.UserID, IM.ClientID, IM.Rate, IM.Title, IM.CID, IM.QTY, IM.DateCompleted, C.Client, U.Name, R.FrequencyUnit, R.FrequencyDuration, R.RBID
ORDER BY IM.DateCompleted ASC;

如果我能澄清任何事情,请告诉我。

提前致谢

4

1 回答 1

1

你有一些选择

  • R.RBID你可以从你的selectandgroup by子句中删除
  • 在 Rate、Title、FrequencyUnit、FrequencyDuration 上创建一个唯一键,这样您就不会得到“相似的项目”
  • 每个 Rate、Title、FrequencyUnit、FrequencyDuration 只获取一个 R.RBID

如果它是您想要的最后一个,您可以使用 row_number 来获取一个且只有一个 RBID(速率、标题、频率单位和频率持续时间)

WITH cte 
     AS (SELECT IM.imid, IM.userid, IM.clientid, IM.rate, 
                IM.title, IM.cid,  IM.qty, IM.datecompleted, 
                C.client, U.name, R.frequencyunit, R.frequencyduration, 
                R.rbid, 
                Row_number() 
                  OVER ( 
                    partition BY R.rate, R.title, R.frequencyunit, R.frequencyduration 
                    ORDER BY R.rbid ) rn 
         FROM   itemmisc IM 
                LEFT JOIN clients C 
                       ON C.clientid = IM.clientid 
                LEFT JOIN users U 
                       ON U.userid = IM.userid 
                LEFT JOIN recurringitem R 
                       ON ( R.clientid = C.clientid 
                            AND IM.rate = R.rate 
                            AND IM.title = R.title ) 
        WHERE   (IM.CID = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#CID#">) 
            AND   (IM.Invoiced = 0)
         GROUP  BY IM.imid, IM.userid, IM.clientid, IM.rate, 
                   IM.title, IM.cid, IM.qty, IM.datecompleted, 
                   C.client, U.name, R.frequencyunit, R.frequencyduration, 
                   R.rbid) 
SELECT * 
FROM   cte 
WHERE  rn = 1 
ORDER  BY im.datecompleted ASC 

注意:您可以通过修改成员来定义“相似项”partition BY

于 2013-03-14T21:49:35.480 回答