SQL Server:连接,重复记录和联盟

时间:2014-01-29 01:59:09

标签: sql sql-server

假设我正在连接表,目的是生成一个已将某些行转换为列的最终表。 FK是外键约束,Info1和Info2用于返回date或null

FK1 | Info1 | Date1
FK1 | Info2 | Date2
FK2 | Info1 | Date1
FK2 | Info2 | Date2

我要返回的表应如下所示:

FK1 | Date1 | Date2
FK2 | Date1 | Date2

相反,返回的是:

FK1 | Date1 | Date2
FK1 | Date1 | Date2
FK2 | Date1 | Date2
FK2 | Date1 | Date2

在阅读了其他一些帖子之后,似乎我需要UNION来实现这一点,但我无法弄清楚在哪里放置它。我的实际查询如下:

select c.idContract,
       c.sgCommonName,
       cl.sgClientTitle,
       cl.sgHomeAddress,
       cl.sgLetterCasual,
       c.sgLotAddress,
       ffd.sgCaption,
       ffv.sgTextValue,
       case when fkidffdefinition = 1161 then dtDateValue end as '11 Day',
       case when fkidffdefinition = 1162 then dtDateValue end as '30 Day'
from 
            tblContracts c
inner join  tblClients cl on cl.idClient = c.fkidClient
inner join  tblFlexFieldValues ffv on ffv.fkidcontract = c.idContract
inner join  tblFlexfieldDefinition ffd on ffd.idFlexFieldDefiniition = ffv.fkidFFDefinition 

where ffd.idFlexFieldDefiniition in (1161,1162)

问题是连接是加入这些值(1161,1162),但我不明白如何“连接”连接(如果这是有意义的)

干杯。

1 个答案:

答案 0 :(得分:3)

不知何故,我认为这是您想要的查询:

select c.idContract, c.sgCommonName, cl.sgClientTitle, cl.sgHomeAddress, cl.sgLetterCasual,
       c.sgLotAddress, ffd.sgCaption, ffv.sgTextValue,
       max(case when fkidffdefinition = 1161 then dtDateValue end) as "11 Day",
       max(case when fkidffdefinition = 1162 then dtDateValue end) as "30 Day"
from tblContracts c inner join
     tblClients cl
     on cl.idClient = c.fkidClient inner join
     tblFlexFieldValues ffv
     on ffv.fkidcontract = c.idContract inner join
     tblFlexfieldDefinition ffd
     on ffd.idFlexFieldDefiniition = ffv.fkidFFDefinition 
where ffd.idFlexFieldDefiniition in (1161, 1162)
group by c.idContract, c.sgCommonName, cl.sgClientTitle, cl.sgHomeAddress, cl.sgLetterCasual,
         c.sgLotAddress, ffd.sgCaption, ffv.sgTextValue;

这是一个聚合查询,它将两个日期放在同一行上。顺便说一下,对列名使用单引号是个坏主意。改为使用双引号或方括号。