【问题标题】:Remove duplicates records from sum statement using SQL server使用 SQL Server 从 sum 语句中删除重复记录
【发布时间】:2020-12-16 05:33:22
【问题描述】:

您好,我有一个表,其中有一些重复记录,我想删除所有重复记录并获取该条件的总数。我在第一个查询中尝试了以下查询,它也将包含重复记录。

1> select count(fd.FarmerRegNo) as TotalRecord,
 sum(case when fd.TSStatus='Approved' and Status!=0  then 1 else 0 end) Approved,
 sum(case when fd.TSStatus='Pending' and fd.Status=0 then 1 else 0 end) Pending,
 from FarmerDetail as fd 

2> select count(distinct FarmerRegNo) as [Approved]  from FarmerDetail where TSStatus='Approved'

查看图像我想在第一个表批准列中获取第二个表值如何删除此条件的重复项

【问题讨论】:

    标签: sql asp.net sql-server count case


    【解决方案1】:

    这是你想要的吗?

    select 
        count(distinct fd.FarmerRegNo) as TotalRecord,
        count(distinct case when fd.TSStatus = 'Approved' and Status != 0   then fd.FarmerRegNo end) Approved,
        count(distinct case when fd.TSStatus = 'Pending'  and Status = 0 then fd.FarmerRegNoend) Pending,
    from FarmerDetail as fd 
    

    【讨论】:

      【解决方案2】:

      使用条件count(distinct):

      select count(fd.FarmerRegNo) as TotalRecord,
             count(distinct case when fd.TSStatus = 'Approved' and fd.Status <> 0 then fd.FarmerRegNo end) as Approved,
             count(distinct case when fd.TSStatus = 'Pending' and fd.Status = 0 then fd.FarmerRegNo end) as Pending,
      from FarmerDetail fd ;
      

      【讨论】:

        【解决方案3】:

        将下面的查询与子查询一起使用

            select count(fd.FarmerRegNo) as TotalRecord,
            (select count(distinct FarmerRegNo) from FarmerDetail where TSStatus='Approved') as Approved,
            sum(case when fd.TSStatus='Pending' and fd.Status=0 then 1 else 0 end) Pending,
            from FarmerDetail as fd
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-07
          • 2016-09-17
          • 1970-01-01
          相关资源
          最近更新 更多