如何组合2个查询?

时间:2016-10-04 20:16:13

标签: sql fastreport

我在fastreport中有以下这些查询。我想将它们组合成一个查询。我怎么能这样做?

SELECT 
    EAMEMID, COUNT (EAMATTNSTATUS)/2 as ABSENTDAYS1
FROM 
    viewDAILYSUM  
WHERE 
    (EAMEMID = :EAMEMID) 
    AND (EAMDATE BETWEEN :FDate AND :TDate)
    AND (EAMATTNSTATUS IN (7, 8))           
GROUP BY 
    EAMEMID  
ORDER BY 
    EAMEMID
SELECT 
    EAMEMID, COUNT(DISTINCT EAMDATE) ABSENTDAYS        
FROM 
    viewDAILYSUM  
WHERE 
    (EAMEMID = :EAMEMID) 
    AND (EAMDATE BETWEEN :FDate AND :TDate)
    AND (EAMATTNSTATUS IN (6))
GROUP BY 
    EAMEMID
ORDER BY 
    EAMEMID

3 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

SELECT EAMEMID,
       SUM(CASE WHEN EAMATTNSTATUS in (7, 8) THEN 1 ELSE 0 END) / 2 as ABSENTDAYS1,
       COUNT(DISTINCT CASE WHEN EAMATTNSTATUS in (6) THEN EAMDATE
             END) as ABSENTDAYS  
FROM viewDAILYSUM  
WHERE (EAMEMID = :EAMEMID) AND
      (EAMDATE between :FDate and :TDate)
GROUP BY EAMEMID  
ORDER BY EAMEMID

答案 1 :(得分:0)

您可以在dinamyc表上进行连接(左边因为两个选择不是同一个eamemid)

select t1.EAMEMID, t1.ABSENTDAYS1, t2.ABSENTDAYS 
from (  SELECT EAMEMID , COUNT (EAMATTNSTATUS)/2 as ABSENTDAYS1
      FROM viewDAILYSUM  
      WHERE (EAMEMID = :EAMEMID) 
        and (EAMDATE between :FDate and :TDate)
        and (EAMATTNSTATUS in (7,8))           
      group by EAMEMID  ) t1
left join ( SELECT EAMEMID ,COUNT(DISTINCT EAMDATE) ABSENTDAYS        
FROM viewDAILYSUM  
WHERE (EAMEMID = :EAMEMID) 
  and (EAMDATE between :FDate and :TDate)
  and (EAMATTNSTATUS in (6))                                                             
group by EAMEMID ) t2  on t1.EAMEMID = t2.EAMEMID
ORDER BY  t1.EAMEMID

答案 2 :(得分:0)

您可以使用 union 相同的方式:

SELECT * FROM
(
  SELECT 
    1 AS NUMQUERY, EAMEMID, COUNT(EAMATTNSTATUS)/2 as ABSENTDAYS
  FROM 
    viewDAILYSUM  
  WHERE 
    (EAMEMID = :EAMEMID) 
    AND (EAMDATE BETWEEN :FDate AND :TDate)
    AND (EAMATTNSTATUS IN (7, 8))           
  GROUP BY 
    EAMEMID

  UNION

  SELECT 
    2, EAMEMID, COUNT(DISTINCT EAMDATE)        
  FROM 
    viewDAILYSUM  
  WHERE 
    (EAMEMID = :EAMEMID) 
    AND (EAMDATE BETWEEN :FDate AND :TDate)
    AND (EAMATTNSTATUS IN (6))
  GROUP BY 
    EAMEMID
)
ORDER BY NUMQUERY, EAMEMID