简体   繁体   中英

Select specific column in an inner join SQL statement

I want to select a specific column ( Name ) from Products on the last inner join I have. How can I do that?

This is my SQL statement:

SqlCommand cmd = new SqlCommand("SELECT * FROM CustomerDetails cd INNER JOIN CustomerProducts cp ON cp.CustomerID = cd.Id INNER JOIN Products p ON cp.ProductID = p.ProductID", conn);

So far I got this, is it possible to have one column for this? Like Name has carbon dioxide, industrial oxygen since they are in the same Id? Thank you

在此处输入图片说明

SqlCommand cmd = new SqlCommand("select p.[name], cd.* FROM CustomerDetails cd Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id Inner Join Products p ON cp.ProductID = p.ProductID", conn);

EDIT: I agree with the comment below, cd.* is not advised, it should be cd.Id, cd.CustomerName... etc.

This should get you the names grouped together in a single column:

;WITH Customers AS
(
    select cd.Id, cd.customer ... FROM CustomerDetails cd 
)

SELECT stuff(
(
    select ', ' + p.[name] FROM Customers cd Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id Inner Join Products p ON cp.ProductID = p.ProductID
    FOR XML PATH('')
), 1, 2, '')
, c.Id, c.CustomerName ...
FROM Customers c
select p.Name, cd.ColumnA, cd.ColumnB, cd.ColumnC
FROM CustomerDetails cd 
Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id 
Inner Join Products p ON cp.ProductID = p.ProductID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM