简体   繁体   中英

Select a column from a different table in SQL Server

I would like to be able to select the column pa.NumberOfPages from dm_package pa in the following select statement. How can I do this?

Select statement 1

    SELECT 
Case When IsPackage = 1 then 'DM, Package' else 'DM' end as FaxType, 
FaxId,  RequestDate, FaxedTo, FaxNumber, Status, ExtendedStatus, StatusDate, 
UserName, IsPackage, DocumentId, -1 as PatientMedicationId, '' as Event, 
'-1' as NCPDPID, 0 as IsEPerscription, -1 as AccessionNumber,
Case When IsPackage = 0 then 
    (Select FilePath from PatientDocument where DocumentId = fl.DocumentId and ( '443' = -1 or '443' = PatientId )) 
    else (Select FilePath from dm_Package where fl.DocumentId = PackageId and ( '443' = -1 or '443' = PatientId )) End as Path, 
Case When IsPackage = 0 then 
    (Select LastFirstName from Patient p, PatientDocument pd where fl.DocumentId = pd.DocumentId and pd.PatientId = p.PatientId) 
    else (select LastFirstName from Patient p, dm_Package pa where fl.DocumentId = pa.PackageId and pa.PatientId = p.PatientId) END as LastFirstName, 
Case When IsPackage = 0 then 
    (select [Description] from PatientDocument where fl.DocumentId = DocumentId and ( '443' = -1 or '443' = PatientId )) 
    else (select PackageName from dm_Package where fl.DocumentId = PackageId and ( '443' = -1 or '443' = PatientId )) End as [Description], 
'' as JobId, -1 as SeqNumber, '' as RefNumber, (select DocId from dbo.PatientDocument pd where fl.DocumentId = pd.DocumentId) as DocId
FROM  dbo.dm_FaxLog fl

Table name dm_package pa

    pa.IsFax, pa.FaxName, pa.faxNumber, pa.FilePath, pa.DocRoot, pa.Note, pa.PatientId, 
    isnull(fl.ExtendedStatus,'') as FaxExtendedStatus, StatusDate as FaxStatusDate, pa.DocId, pa.NumberOfPages 

Are you familiar with how to join tables in SQL?

http://technet.microsoft.com/en-us/library/ms191517(v=sql.105).aspx

select a.data1, b.data2
from a_table a
join b_table b on a.data3 = b.data3

I assume FaxNumber in dm_FaxLog and dm_package are same. Then you can do -


SELECT f1.faxNumber, pa.NumberOfPages --list other required columns 
FROM   dm_FaxLog fl
INNER JOIN dm_package pa ON pa.faxNumber = f1.faxNumber

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM