如何使用GROUP BY为字段制作逻辑/我可以使用文本字段作为SQL逻辑吗?

时间:2011-03-22 07:16:19

标签: sql tsql sql-server-2008

我在这里:

SELECT [RecTime], [Name],
   CAST(CASE WHEN 
   -- <logics>
    1=0 -- ???
    -- </logics>
   THEN 1 ELSE 0 END AS bit) AS [Value]
FROM EventIncidentsStates
GROUP BY [RecTime], [Name]

EventIncidentsStates看起来像这样:

        RecTime                    SQL                Event        Name       Val
2011-03-02 08:36:10.047 | Alarm1002 AND Alarm1004 | Alarm1002 | doubleAlarm  | 1
2011-03-02 08:36:10.047 | Alarm1002 AND Alarm1004 | Alarm1004 | doubleAlarm  | 0
2011-03-02 08:36:10.047 | Alarm1002               | Alarm1002 | myalarm1002  | 1
2011-03-02 08:36:20.030 | Alarm1002 AND Alarm1004 | Alarm1002 | doubleAlarm  | 1
2011-03-02 08:36:20.030 | Alarm1002 AND Alarm1004 | Alarm1004 | doubleAlarm  | 0
2011-03-02 08:36:20.030 | Alarm1004               | Alarm1004 | TestIncident | 0
2011-03-02 08:36:40.050 | Alarm1002 AND Alarm1004 | Alarm1002 | doubleAlarm  | 0
2011-03-02 08:36:40.050 | Alarm1002 AND Alarm1004 | Alarm1004 | doubleAlarm  | 0
2011-03-02 08:36:40.050 | Alarm1004               | Alarm1004 | TestIncident | 0

Val是Event的值,而不是Name的值,我需要通过SQL逻辑和分组获得Name的值。

嗯,让我来解释一下第一个节点的例子,

第一个字段是RecTime,第二个字段是 Alarm1002 AND Alarm1004 这必须是逻辑:)也可能看起来很相似(Alarm1002 = 1 AND Alarm1004 = 1) ,不确定我是否可以使用它, doubleAlarm 名称 ,具有此逻辑的复杂事件的名称,

即使有这个时间的事件,

Alarm1002 is 1
Alarm1004 is 0

所以 doubleAlarm 的[Value]应该是(1 AND 0)= 0 ......我知道我的结构有点奇怪,但任务非常复杂:)

毕竟这个问题包含2个问题,我很乐意在任何问题上得到答案:

  1. 如何使用GROUP BY的自定义逻辑
  2. 如何解析nvarchar字段到SQL逻辑,是的第二个问题是一种令人头疼的问题

    另一个例子:

    -- Example
        SELECT [RecTime], [Name],
           CAST(CASE WHEN 
           -- <logics>
           [SQL]
           -- </logics>
           THEN 1 ELSE 0 END AS bit) AS [Value]
        FROM EventIncidentsStates
        GROUP BY [RecTime], [Name], [SQL]
    
    
    
    -- Inital data
    
    EventIncidentsStates -
    
    [RecTime]         [SQL]                [EventName] [Value] [Name]
    SomeDate (EVENT1 = 1 AND EVENT2 = 1)     EVENT1       1      Some
    SomeDate (EVENT1 = 1 AND EVENT2 = 1)     EVENT2       0      Some
    
    -- Out data
    
    SomeDate Some 0
    

1 个答案:

答案 0 :(得分:2)

Asn第一个问题

利用Case.. when amy解决您的问题

USE AdventureWorks2008R2;
GO
SELECT JobTitle, MAX(ph1.Rate)AS MaximumRate
FROM HumanResources.Employee AS e
JOIN HumanResources.EmployeePayHistory AS ph1 ON e.BusinessEntityID = ph1.BusinessEntityID
GROUP BY JobTitle
HAVING (MAX(CASE WHEN Gender = 'M' 
        THEN ph1.Rate 
        ELSE NULL END) > 40.00
     OR MAX(CASE WHEN Gender  = 'F' 
        THEN ph1.Rate  
        ELSE NULL END) > 42.00)
ORDER BY MaximumRate DESC;