SQL Count Distinct具有多个条件,以返回所有列,所有记录

时间:2018-12-29 00:19:28

标签: sql-server tsql

早上好,我正在尝试计算给定条件下不同值的数量,但是,我需要查询结果包括所有列和记录。基本上,非重复计数结果将作为新列添加到原始表中,并且仅对每一行重复一次。

这是我到目前为止的内容,我无法进行下一步。我有三张桌子连在一起。考虑到R.ID(来自tbl_reqtype)和R.DocumentNo(来自tbl_reqtype)是相同的,我想计算tbl_trantype中唯一的T.CostCenter。

SELECT M.[ID] AS EMLID
        ,R.[ID] AS RequestID
        ,T.[ID] AS TransactionID
        ,R.[DocumentNo]
        ,T.[CostCenter]
        ,ROW_NUMBER() OVER (PARTITION BY R.ID, R.DocumentNo, T.CostCenter ORDER BY T.ID) NoOfCostCenter 
FROM (tbl_Info M
        INNER JOIN tbl_reqtype R ON M.ID = R.EMLID)
        INNER JOIN tbl_trantype T ON R.ID = T.RID

下面是我希望的结果

EMLID   RequestID   TransactionID   DocumentNo  CostCenter  NoOfCostCenter
4000001    11           1           777777777   1515151         2
4000001    11           2           777777777   1515151         2
4000001    11           3           777777777   4515151         2
4000003    12           4           999999999   7277477         5
4000003    12           5           999999999   7277477         5
4000003    12           6           999999999   8722724         5
4000003    12           7           999999999   7272726         5
4000003    12           8           999999999   2652627         5
4000003    12           9           999999999   6353636         5

1 个答案:

答案 0 :(得分:1)

<罢工> 看来您很亲密。我会使用以下查询:

SELECT M.[ID] AS EMLID
        ,R.[ID] AS RequestID
        ,T.[ID] AS TransactionID
        ,R.[DocumentNo]
        ,T.[CostCenter]
        ,COUNT(DISTINCT T.CostCenter) OVER (PARTITION BY R.ID, R.DocumentNo) NoOfCostCenter 
FROM (tbl_Info M
        INNER JOIN tbl_reqtype R ON M.ID = R.EMLID)
        INNER JOIN tbl_trantype T ON R.ID = T.RID

我只是将ROW_NUMBER替换为COUNT(并删除了与计数无关的ORDER BY,并删除了我们正在计数的内容,从分区开始)。

但是我不确定,因为您没有提供输入的详细信息。

编辑:很抱歉,我忘记了这是T-SQL,而不是Oracle DB SQL,因此DISTINCT子句将不起作用。 您可能会发现此答案有帮助:raw interface

该问题的解决方案/答案之一将适用于以下情况:

SELECT M.[ID] AS EMLID
        ,R.[ID] AS RequestID
        ,T.[ID] AS TransactionID
        ,R.[DocumentNo]
        ,T.[CostCenter]
        ,DENSE_RANK()
           OVER (PARTITION BY R.[ID], R.[DocumentNo] ORDER BY T.[CostCenter])
         + DENSE_RANK()
           OVER (PARTITION BY R.[ID], R.[DocumentNo] ORDER BY T.[CostCenter] DESC)
         - 1 as [NoOfCostCenter]
  FROM (tbl_Info M
        INNER JOIN tbl_reqtype R ON M.ID = R.EMLID)
        INNER JOIN tbl_trantype T ON R.ID = T.RID
 ORDER BY [TransactionID]

Window functions to count distinct records显示结果(具有简化的源/输入结构)。