加入精选语句?

时间:2016-06-29 11:02:15

标签: sql sql-server

我想在查询中进行内部联接,但我不知道如何将两个select语句汇总到一个查询中。

这是第一个查询:

 select 
          Machine  
        , EventDefinition
        , Duration
        , sum(Duration) over (partition by 1) As Total
        , Duration/sum(Duration) over (partition by 1)*100 AS Distribution
        ,case when EventCategory < 0.05 Then 'NOT INCL' ELSE 'OK' END AS Under3Min

     from (

           Select 
    SystemName AS Machine
    , EventDefinition
    , EventDate
    , EventStartDateTime
    , IsNull(EventEndDateTime, GETDATE()) as EventEndDateTime
    , Sum(cast(EventEndDateTime - EventStartDateTime as float))*24 as Duration
    ,Sum(case when CustomEvent = 'without Stop' then cast(EventEndDateTime - EventStartDateTime as float)*24 else 0 end) as EventCategory
        FROM tDataCategory                  
        WHERE EventDate >= @StartDateTime
        AND EventDate <= @EndDateTime
        AND SystemName = '201'
Group BY SystemName, eventdefinition, eventstartdatetime,  eventenddatetime, EventDefinition, EventDate, CustomEvent
    ) as t
    WHERE CustomEvent <> 'without Stop' 
        OR (CustomEvent = 'without Stop' AND t.EventCategory >=0.05)

    group by EventDefinition
            , Duration
        ,Machine
        ,EventCategory

输出: enter image description here 和我的第二个问题:

   SELECT DataValue = case when Prod = 0 then 0 else ISNULL(100.0 / Prod * Scrap, 0) end, 
    Value = GoodUnits/TheoreticalUnits *100, 
        FROM (
        Select intervaldate as DateValue, intervalDateWeek as Datum, tsystem.Name as Name, ProductName as Product, teamname as Team,
    SUM(case when IssueName in ('A1', 'A2') then calculationUnitsInitial else 0 end) as Scrap,
    Sum(case when IssueName = 'Prod' then calculationUnitsInitial else 0 end) as Prod,
    SUM(GoodUnits) 

As GoodUnits,
SUM(TheoreticalUnits) As TheoreticalUnits,

from tCount inner join tsystem ON tCount.systemid = tsystem.id
    where IntervalDate >=  dateadd(wk, datediff(wk, 1, getdate()), 0)  
and IntervalDate <= dateadd(wk, datediff(wk, 0, getdate()), 0)
AND ((DATEPART(dw, IntervalDate) + @@DATEFIRST) % 7) NOT IN (0,1)
    and tsystem.Name = '201'

    group by intervaldate, tsystem.Name, intervaldateweek, ProductName, teamname
    ) as s

输出: enter image description here

我尝试在我的查询中添加两个select语句。但是,如果我这样做,输出是错误的。我真的不知道如何加入这两个问题。

我想做这个计算:Distribution * (1 - Value)

来自第一个查询的

Distribution和来自第二个查询的Value

1 个答案:

答案 0 :(得分:1)

我假设第一个和第二个结果集必须基于A.Machine = B.Name

加入

试试这个,

Local Terminal