SQL两个选择查询两个表作为一个结果4个字段

时间:2018-01-30 08:59:41

标签: sql reporting-services

美好的一天

请你帮忙,我有两张桌子的结构完全相同但是一张基本上是另一张的副本,我称之为“原创”,因为现场更新。我需要对每个表的相同字段进行计数,但需要使用其唯一的日期。所以我想要每个表的计数和日期字段,但在一个结果中,即4个字段。我需要这个SSRS报告,我很忙。

我已尝试过联盟,但它只计入一行,并将其显示在一个带有一个日期的字段中。

我的查询如下:

Select count (payhist.AC_CODEID) as Actual,PAYHIST.PH_DATE as d1 from PAYHIST
join Paymonth on PAYHIST.PH_DATE >= Paymonth.ph_datesd  and  PAYHIST.PH_DATE <= Paymonth.ph_dateed 
where Paymonth.CurrentPD = 1
and PH_EXCEPTION = 1



Select count (PAYHISTTEMP.MST_SQ) as Original,PAYHISTTEMP.PH_DATE as d2  from PAYHISTTEMP
join Paymonth on PAYHISTTEMP.PH_DATE >= Paymonth.ph_datesd  and  PAYHISTTEMP.PH_DATE <= Paymonth.ph_dateed 
where Paymonth.CurrentPD = 1)
 group by PAYHISTTEMP.PH_DATE) 

3 个答案:

答案 0 :(得分:0)

另一种方式,

  SELECT DATE, SUM(COUNT1) AS COUNT1, SUM(COUNT2) AS COUNT2
    FROM (
     SELECT DATE, COUNT1, 0 AS COUNT2 
       FROM TABLE1 WHERE .... GROUP BY DATE
      UNION ALL
     SELECT DATE, 0 AS COUNT1, COUNT2 
       FROM TABLE2 WHERE .... GROUP BY DATE
  ) TMP
  GROUP BY DATE

答案 1 :(得分:0)

你可以使用它。

SELECT ISNULL(Act.Actual,0) Actual, Act.d1, ISNULL(Org.Original,0) Original, Org.d2 FROM 
(
    Select count (payhist.AC_CODEID) as Actual,PAYHIST.PH_DATE as d1 from PAYHIST
    join Paymonth on PAYHIST.PH_DATE >= Paymonth.ph_datesd  and  PAYHIST.PH_DATE <= Paymonth.ph_dateed 
    where Paymonth.CurrentPD = 1
    and PH_EXCEPTION = 1
    GROUP BY PAYHIST.PH_DATE 
) AS Act
FULL JOIN 
(
    Select count (PAYHISTTEMP.MST_SQ) as Original,PAYHISTTEMP.PH_DATE as d2  from PAYHISTTEMP
    join Paymonth on PAYHISTTEMP.PH_DATE >= Paymonth.ph_datesd  and  PAYHISTTEMP.PH_DATE <= Paymonth.ph_dateed 
    where Paymonth.CurrentPD = 1
     group by PAYHISTTEMP.PH_DATE
) AS Org ON Act.d1 = Org.d2

答案 2 :(得分:0)

在日期列上加入两个select语句。试试这个

 SELECT * FROM

(Select COUNT(payhist.AC_CODEID) AS Actual,PAYHIST.PH_DATE as d1 FROM PAYHIST
   JOIN Paymonth ON PAYHIST.PH_DATE >= Paymonth.ph_datesd  AND
   PAYHIST.PH_DATE  <= Paymonth.ph_dateed 
   WHERE Paymonth.CurrentPD = 1 AND PH_EXCEPTION = 1
) t1

INNER JOIN

(SELECT COUNT (PAYHISTTEMP.MST_SQ) AS Original,PAYHISTTEMP.PH_DATE AS d2  FROM PAYHISTTEMP
JOIN Paymonth on PAYHISTTEMP.PH_DATE >= Paymonth.ph_datesd  AND PAYHISTTEMP.PH_DATE <= Paymonth.ph_dateed 
WHERE Paymonth.CurrentPD = 1
 GROUP BY PAYHISTTEMP.PH_DATE) t2
ON t1.d1 = t2.d2