我非常感谢有关如何处理连接不返回笛卡尔积的表但将下面的居民放入单个返回行的列的查询的一些指示。我需要生成一些报告,我需要在每个空间的一个报告中让所有相关的居民来自一个空间。我没有任何示例代码,因为我不确定从哪里开始。
空格表
spaceID|rent | name
--------------------------------
1 |1000 |Joe Smith
1 |1000 |Jane Smith
etc...
居民表
-targets: [{% for ip in host_ips %}'{{ ip }}:5051'{{ "," if not loop.last else "" }} {% endfor %}]
预期结果
SELECT ...
FROM ....
INNER JOIN (SELECT '2017-12-01' AS beginDate, '2017-12-30' AS endDate) AS dr
ON (ship.dateShipped BETWEEN dr.beginDate AND dr.endDate)
OR (fulfill.datefulfilled BETWEEN dr.beginDate AND dr.endDate)
...
使用联接的结果
lesshint
答案 0 :(得分:0)
这适合你,但它依赖于假设空间中的每个居民都有顺序ID号 - 因此这样就不是一般的查询。它在语法上也有些混乱,因为Access SQL没有利用一些比T-SQL更强大的工具。 我真的会在Excel中执行此操作,它具有内置的透视功能。
SELECT tA.spaceID, tA.rent, tA.resident, tC.resident, tD.resident
FROM (((SELECT tblSpaces.spaceID, tblSpaces.rent, tblResidents.resident, tblResidents.id
FROM tblResidents LEFT JOIN tblSpaces ON tblResidents.spaceID = tblSpaces.spaceID) AS tA
INNER JOIN (SELECT spaceID, MIN(id) AS minID
FROM tblResidents
GROUP BY spaceID) AS tB ON tA.id = tB.minID)
LEFT JOIN tblResidents AS tC ON tC.id = tA.id + 1 AND tC.spaceID = tA.spaceID)
LEFT JOIN tblResidents AS tD ON tD.id = tA.id + 2 AND tD.spaceID = tA.spaceID
请注意,我已将您的表名修改为tblSpaces
和tblResidents
。
答案 1 :(得分:-2)
使用Stuff Method获得所需的结果。
IF OBJECT_ID('tempdb..#Spaces') IS NOT NULL
DROP TABLE #Spaces
IF OBJECT_ID('tempdb..#Resident') IS NOT NULL
DROP TABLE #Resident
create table #Spaces
(
spaceID int,
rent decimal
)
create table #Resident
(
ID int,
SpaceID int,
ResidentName varchar(50)
)
insert into #Spaces values(1,1000),(2,1200)
insert into #Resident values(1,1,'Joe Smith'),(2,1,'Jane Smith'),(3,2,'Frank Zakk'),(4,2,'Nancy Zakk'),(5,2,'Sam Zakk')
Select spaceID, rent,ResidentName=STUFF((SELECT ' | ' + ResidentName
FROM #Resident b
WHERE b.SpaceID = a.SpaceID
FOR XML PATH('')), 1, 2, '')
from(
select A.spaceID,A.rent,B.ResidentName from #Spaces A
inner join #Resident B
on A.spaceID=B.SpaceID)a
group by spaceID,rent