2016-01-03 80 views
0

我想要得到的百分比可以接受的,優秀的,notacceptable,使用下面的查詢,但答案是重複獲取SQL查詢值重複

begin 
    set nocount on 

    declare @acceptable as varchar(10) 
    declare @Excellent as varchar(10) 
    declare @NotAcceptable as varchar(10) 

    declare @total as varchar(10) 

    declare @percent1 as varchar(10) = null 
    declare @percent2 as varchar(10) = null 
    declare @percent3 as varchar(10) = null 

    select @acceptable = count(*) 
    from [dbo].[tbl_Apprisal] 
    where ApprisalStatus = 'Acceptable' 

    select @Excellent = count(*) 
    from [dbo].[tbl_Apprisal] 
    where ApprisalStatus = 'Excellent' 

    select @NotAcceptable = count(*) 
    from [dbo].[tbl_Apprisal] 
    where ApprisalStatus = 'Not Acceptable' 

    SET @total = convert(decimal, @acceptable) + 
       convert(decimal, @Excellent) + 
       convert(decimal, @NotAcceptable) 

    SET @percent1 = convert(int, @acceptable) * convert(int, 100)/convert(int, @total) 
    SET @percent2 = convert(int, @Excellent) * convert(int, 100)/convert(int, @total) 
    SET @percent3 = convert(int, @NotAcceptable) * convert(int, 100)/convert(int, @total) 

    select 
     'Accplable:' + @percent1 + '%' + ',' + 'Excellent:' + @percent2 + '%' + ',' + 'Not Acceptable:' + @percent3 + '%' as persnt, 
     Emp.personFname as doneby1, 
     Em.personFname + Em.[personMname] + Em.[personLname] as personFname1, 
     ap.ProcessId, ap.empNumber, 
     ap.fromDate ApprisalStatus, ap.comment, ap.DoneBy, 
     convert(date, ap.DoneByDate, 105) as DoneByDate 
    from 
     [dbo].[tbl_Apprisal] ap 
    inner join 
     [dbo].[tbl_EmployeePersonalDetails] Em on Em.empNumber = ap.empNumber 
    inner join 
     [dbo].[tbl_EmployeePersonalDetails] Emp on Emp.empNumber = ap.DoneBy 
    order by 
     convert(date, ap.fromDate, 105) DESC 

在這個SQL查詢中值重複,請幫助我解決這個問題

+3

什麼值重複?你看到的價值是什麼,你期望的是什麼? –

+0

如果使用觸發器或PROC ....加入這一行SET NOCOUNT關 https://msdn.microsoft.com/en-us/library/ms189837.aspx –

+0

合併數爲[單一的選擇,使用的情況下] (http://stackoverflow.com/questions/1400078/is-it-possible-to-specify-condition-in-count)避免閱讀表三次。 –

回答

0

好,從我看到你有SQL問題不是C#。

在這樣的情況下,我往往有錯誤的JOIN我的查詢,知道的最好的方法是什麼錯誤是寫新的選擇,看看行復制:

select 
    -- AP primary key 
    ap.? 
    -- Em primary key 
    em.? 
    -- Emp primary key 
    emp.? 
from 
    [dbo].[tbl_Apprisal] ap 
inner join [dbo].[tbl_EmployeePersonalDetails] Em on Em.empNumber = ap.empNumber 
inner join [dbo].[tbl_EmployeePersonalDetails] Emp on Emp.empNumber = ap.DoneBy 

請檢查什麼每個連接表都是pk。你應該有一個EM和PK每PK PK。你顯然沒有這種情況,所以我看到兩種選擇。要麼你可以嘗試編寫正確的連接,以確保行不會加倍本身,或者如果這是不可能的(例如,一個員工可以有很多個人信息),你可以決定要在子查詢distpal並加入到它其中一個。這樣的事情:

select 
[..] 
from 
    [dbo].[tbl_Apprisal] ap 
inner join (
    SELECT 
     empNumber, 
     MAX(personFname) as personFname 
    FROM 
     [dbo].[tbl_EmployeePersonalDetails] 
    GROUP BY 
     empNumber 
) Em on Em.empNumber = ap.empNumber 
[..] 

希望這會有所幫助。