如何并排显示两个表的记录

时间:2015-07-02 15:27:01

标签: sql sql-server

我有App表和Apphistory表我需要显示应用程序记录和应用程序历史记录并排列

        $config = $di->getShared('config')->mongo;
        $connect_data = $config->username . ':' . $config->password . '@' . $config->host . ':' . $config->port . '/' . $config->dbname;
        $mongo = new \MongoClient("mongodb://" . $connect_data);
        return $mongo->selectDB($config->dbname);

但是我的问题是当App表中有Appno而App曲目表中没有App我将从App表中显示记录。 当两个表中都有记录时,我需要使用Apphistory表中的值显示相同app no的旧记录

out put应该像:

declare @app table (Appno varchar(10),Name varchar(10),Height INT,weight INT,Createddate datetime)
insert into @app (Appno,Name,Height,weight,Createddate)values 
('app1035','tom',10,60,'2015-07-02 20:14:45.590'),
('app1036','john',8,40,'2015-07-02 20:14:45.590'),
('app1037','jim',9,36,'2015-07-02 20:14:45.590')

declare @apphistory table 
(
Appno varchar(10),
Name varchar(10),
Height INT,
weight INT,
Createddate datetime)
insert into @apphistory (Appno,Name,Height,weight,Createddate)
values('app1035','tom',10,60,'2015-07-02 20:14:45.590')
,('app1035','tom',8,45,'2015-06-02 20:14:45.590'),
('app1035','tom',6,NULL,'2015-05-02 20:14:45.590'),
('app1036','john',8,40,'2015-07-02 20:14:45.590')
,('app1036','john',8,40,'2015-06-02 20:14:45.590'),
('app1036','john',NULL,NULL,'2015-05-02 20:14:45.590')

select A.Appno, COALESCE(H.Appno,A.Appno)HAppno,
A.Name,COALESCE(H.Name,A.Name)Hname,
A.Height,COALESCE(H.Height,A.Height)Hheight,
A.weight,COALESCE(H.weight,A.weight)Hweight,
A.Createddate,COALESCE(H.Createddate,A.Createddate)Hcreateddate

FROM @app A LEFT JOIN  (select top 1 Appno,Name,Height,weight,Createddate from @apphistory ORDER BY Createddate  )H
ON  A.Appno = H.Appno
WHERE A.Appno = 'app1036'

2 个答案:

答案 0 :(得分:0)

使用ROW_NUMBER()功能按创建日期提取最早的记录。 Fiddle sample

;WITH CTE AS
(
   SELECT *, ROW_NUMBER() OVER (PARTITION BY Appno ORDER BY CreatedDate) rn
   FROM @apphistory
)
SELECT a.*, h.*
FROM @app a
        LEFT JOIN CTE h ON a.Appno = h.Appno AND h.rn = 1

您可以使用Coalesce()函数填充空值,并为您的首选项订购选择列列表。

答案 1 :(得分:0)

以下是我建议的简化代码示例:

SELECT a.AppNo, COALESCE(ah.Height, a.Height) AS Height 
FROM App a
LEFT OUTER JOIN (
  SELECT AppNo, COALESCE(Height, 'NULL') AS Height
  FROM AppHistory
) ah
  ON a.AppNo=ah.AppNo

我意识到这在原始问题中遗漏了很多逻辑,我只是​​想说明我在评论中提到的分层Coalesce技术。