Concatenating rows from an alias computed column

2019-07-09 19:55发布

I have two tables, one named Car and one named Mileage. Car table has the following column:
CarName varchar(max)
Mileage table has the following columns:
CarMileage int CarName varchar(max) TotalGasTrips int

My code is the following:

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 

The query result is:

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

The result I want is:

CarName     MPGString
Acura NSX    20,42
Pagani Zonda 24,43

Is it possible to get the correct concatenated rows I want from aliased computed columns? I tried looking all over and all I found was concatenation from columns that already had existing values and not from computed columns. Thanks for your help.

Edit:
Both tables have the same car names ( in this instance Acura NSX and Pagani Zonda).To test the string concatenation, I gave the same two cars different numbers for TripGasTrips and CarMileage. An example is the following in the Mileage table:
Acura NSX 125471,6172 Acura NSX 213776,5000 Pagani Zonda 166793, 6911 Pagani Zonda 315531 7312

with the columns being CarName, CarMileage and TotalGasTrips respectively and in the Car Table I have the following:
Acura NSX Pagani Zonda
with CarName being the only column for the table.
Edit:
Output from the c table is as follows:

CarName MPG Acura NSX 20 Acura NSX 42 Pagani Zonda 24 Pagani Zonda 43

1条回答
爷、活的狠高调
2楼-- · 2019-07-09 20:53

This works for me (it would be easier if you gave some data to test with):

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
查看更多
登录 后发表回答