我有两个表,一个名为Car,另一个名为Mileage。车载表格包含以下列:
CarName varchar(max)
里程表包含以下列:
CarMileage int
CarName varchar(max)
TotalGasTrips int
我的代码如下:
SELECT DISTINCT y.CarName,
Substring((SELECT ', ' + Cast(c.MPG AS VARCHAR(max))
FROM Mileage
JOIN Car
ON Mileage.CarName = Car.CarName
WHERE Mileage.CarName = Car.CarName
FOR xml path ('')), 2, 1000) AS MPGString
FROM Car y
INNER JOIN (SELECT w.CarName,
CarMileage / TotalGasTrips AS MPG
FROM Mileage w
GROUP BY w.CarName,
w.CarMileage,
w.TotalGasTrips)c
ON y.CarName = c.CarName
GROUP BY c.MPG,
y.CarName
查询结果为:
CarName MPGString
Acura NSX 20,20,20,20
Acura NSX 42,42,42,42
Pagani Zonda 24,24,24,24
Pagani Zonda 43,43,43,43
我想要的结果是:
CarName MPGString
Acura NSX 20,42
Pagani Zonda 24,43
是否有可能从别名计算列中获取我想要的正确连接行?我试着查看全部,我发现的所有内容都是来自已有现有值但不是来自计算列的列的连接。谢谢你的帮助。
修改
两个表都有相同的车名(在这个例子中是Acura NSX和Pagani Zonda)。为了测试字符串连接,我为TripGasTrips和CarMileage提供了相同的两辆车不同的号码。里程表中的以下示例如下:
Acura NSX 125471,6172
Acura NSX 213776,5000
Pagani Zonda 166793, 6911
Pagani Zonda 315531 7312
列分别为CarName,CarMileage和TotalGasTrips
在汽车表中我有以下内容:
Acura NSX
Pagani Zonda
CarName是表格的唯一列。
修改
c表的输出如下:
CarName MPG
Acura NSX 20
Acura NSX 42
Pagani Zonda 24
Pagani Zonda 43
答案 0 :(得分:0)
这对我有用(如果您提供一些数据进行测试会更容易):
SELECT
C.CarName,
SUBSTRING((
SELECT
', ' + CAST(CarMileage / TotalGasTrips AS VARCHAR(MAX))
FROM
Mileage
WHERE
Mileage.CarName = C.CarName
GROUP BY
dbo.Mileage.CarMileage,
dbo.Mileage.TotalGasTrips
FOR
XML PATH('')
), 2, 1000) AS MPGString
FROM
Car C
JOIN dbo.Mileage M ON C.CarName = M.CarName
GROUP BY
C.CarName