2011-03-31 55 views
0

我已經得到了3個表:多個結果的查詢爲csv串在新的列

用戶,產品user2product

每個產品得到了ID。

是否有可能寫的查詢中,作爲結果,我會得到2列:

UserID, Products 

而且在產品的專欄中,我必須用逗號分隔user2product表連接到用戶的所有產品。

+1

你想在T-SQL或Linq中寫? – msarchet 2011-03-31 14:19:52

回答

0

什麼SQL方言,我們談論的? 對於PostgreSQL,有一個非常全面的答案,在這裏找到: How to concatenate strings of a string field in a PostgreSQL 'group by' query?

對於其他SQL的系統的思路應該是大同小異的。您將不得不搜索正確的聚合函數,其他所有操作都可以使用簡單的group by指令完成。

乾杯 蒂洛

+0

剛剛看到SQL-Server標記,因此它可能不會是Postgres。不過,這個想法應該成立。 – Thilo 2011-03-31 14:31:05

0

它很可能爲此使用本地TSQL使用for xml path語句詳細here

要訪問此通過LINQ創建一個數據庫中的存儲過程,將其拖動到您的dbml文件,然後像方法一樣從數據上下文中調用它。

對SP的代碼會是這個樣子

select 
    u.userid, 
    substring((select ',' + cast(p.productid as nvarchar(20)) 
     from 
      user2product up inner join 
      product p on up.productid = p.productid 
     where 
      up.userid = u.userid 
     for xml path('')),2,2000000) as Products 
from 
    users u