如何基于SQL列值进行分类

时间:2016-12-19 18:16:02

标签: sql sql-server

我希望得到分行中女性的比率基本上看起来像这样:

BranchID   | CountOfWomen   | CountofMen      | CountOfWomen/CountOfMen
(B001),           (3),            (4),                  (0.75)
(B002),           (1),            (1),                   (1)

所以现在我有一个分行的女性比率: B001雇主中有75%是女性...... 我现在需要的是:

费率(CountOfWomen / CountOfMen)分为3类:Avarage,Low,High

Avarage意味着IF CountOfWomen / CountofMen为1,因此1:1的比率

低意味着IF CountOfWomen / CountofMen <1

高意味着如果CountOfWomen / CountofMen> 1 ...... ......工作的男性比女性更多......

我试过以下:

我正在尝试创建一个视图并将值放在已定位的列中,但它不起作用!!

   CREATE VIEW MFKata2 (BranchID,High,Low,Avarage ) AS
    SELECT       MFKata.BranchID,
    Case When(MFKata.Quote > 1) As High,
    Case When (MFKata.Quote < 1) As Low,
    Case When (MFKata.Quote = 1) As Avarage
    FROM         MFKata  

引用是率(CountOfWomen / CountOfMen)我刚刚在这里重命名它以便更好地解释!

这是创建MFKata的代码:

CREATE VIEW MFKata (BranchID,AnzahlF, AnzahlM,Quote ) 
AS
SELECT    Frauen2.BranchID
        , AnzahlF
        , AnzahlM
        , CAST(AnzahlF as float)/CAST(AnzahlM as float) as Quote
FROM  Frauen2  
INNER JOIN Maenner ON Frauen2.BranchID = Maenner.BranchID

1 个答案:

答案 0 :(得分:4)

您的所有案例陈述都缺少END

 CREATE VIEW MFKata2 (BranchID,High,Low,Avarage ) AS
    SELECT       MFKata.BranchID,
    Case When (MFKata.Quote > 1) THEN 1 END AS High,
    Case When (MFKata.Quote < 1) THEN 1 END As Low,
    Case When (MFKata.Quote = 1) THEN 1 END As Avarage
    FROM 

或者你可以有一个列为高/低/平均值,像......一样......

 CREATE VIEW MFKata2 (BranchID,[Rate]) AS
    SELECT       MFKata.BranchID,
    Case When (MFKata.Quote > 1) THEN 'High'
         When (MFKata.Quote < 1) THEN 'Low'
         When (MFKata.Quote = 1) THEN 'Avarage' 
      END AS [Rate]
    FROM 

修改

除非绝对必要,否则避免在视图之上创建视图,这可以通过非常简单的选择查询来实现。有点像......

SELECT  BranchID
      , Case 
           When (Quote > 1) THEN 'High'
           When (Quote < 1) THEN 'Low'
           When (Quote = 1) THEN 'Average' 
        END AS [Rate]
FROM (
    SELECT    Frauen2.BranchID
            , AnzahlF
            , AnzahlM
            , CAST(AnzahlF as float)/CAST(AnzahlM as float) as Quote
    FROM  Frauen2  
    INNER JOIN Maenner ON Frauen2.BranchID = Maenner.BranchID
    ) A