如何在SQL中将行追加到SELECT查询中?

时间:2018-06-13 13:18:42

标签: sql sql-server sql-server-2012

我有一个查询,它给了我想要的结果。列名是这样的(我从查询中得到):

RXID |DrName |SBOID |SBOName |RxHonoredDate |RxnHonoured |CallRecievedFrom |MobileNo    

现在我有一个名为'SampleRepeat'的表。这有以下列

DrID |  CallRecievedFrom |  Mobile | SBOID  |RxnHonoured

(此处我们从表DrNameDrIDTblDr提取SBONameSBOID

这是我的疑问:

select G.RXID, NoOfRx, DrName,HospitalName,G.EmpCode AS SBOID ,TM_Name AS SBOName,CONVERT(DATETIME,H.CreatedDate) AS RxHonoredDate, DrSpeciality AS Speciality,
convert(DATETIME, G.CreatedDate) AS [RxGeneratedDate],COALESCE(H.rows, 0) AS RxnHonoured,
CallRecievedFrom,MobileNo ,G.HQ
from(
select RXID,SUM(RxGenerate) as NoOfRx, DrName,HospitalName,RX.EmpCode,TE.TM_Name,   DrSpeciality,convert(DATE,RX.CreatedDate)as CreatedDate,TE.Territory AS HQ
from tbl_rx RX
  left join tblEmployee TE on  TE.TM_Emp_Id=RX.EmpCode
GROUP BY RX.EmpCode,RX.DrName,RX.HospitalName,RX.CreatedDate,RX.DrSpeciality,TE.TM_Name,RX.RXID,TE.Territory 
)G
left join
( SELECT EmpCode,DrID,CreatedDate, SUM(MedToPCount) AS rows,CallRecievedFrom,MobileNo FROM tbl_MedicinToPatient WHERE Status = 'Delivered' GROUP BY EmpCode,DrID,CreatedDate,CallRecievedFrom,MobileNo
)H 
on H.DrID=G.RXID ORDER BY TM_Name, H.CreatedDate ASC

我想将此表值附加到查询结果的末尾,所有其他列将为null。 我试过Union all但没有成功。我怎么做?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

带有计算列的{p> UNION ALLSELECT * FROM ( SELECT OrderID = 1 RXID, DrName, SBOID, SBOName, RxHonoredDate, RxnHonoured, CallRecievedFrom, MobileNo FROM Query Q UNION SELECT OrderID = 2 RXID = NULL, DrName = DrID, SBOID = NULL, SBOName = SBOID, RxHonoredDate = NULL, RxnHonoured, CallRecievedFrom, MobileNo = Mobile FROM SampleRequest) AS X ORDER BY OrderID 应该有效。

ItemsSource

答案 1 :(得分:1)

确保SELECT中每列的订单和数据类型匹配。

SELECT
    RXID,
    DrName,
    SBOID,
    SBOName,
    RxHonoredDate,
    RxnHonoured,
    CallRecievedFrom,
    MobileNo
FROM
    YourFirstTable AS T
UNION ALL
SELECT
    RXID =  NULL,
    DrName =  NULL,
    SBOID =  T.SBOID,
    SBOName =  NULL,
    RxHonoredDate =  NULL,
    RxnHonoured =  T.RxnHonoured,
    CallRecievedFrom =  T.CallRecievedFrom,
    MobileNo =  T.Mobile
FROM
    YourSecondTable AS T