如何获得每组一件商品?

时间:2013-04-28 14:57:48

标签: sql-server tsql group-by

我有两张表如下:

表1:字段(FieldID,FormID,Title,DateCreated,...)

表2:值(ValueID,FormID,FieldID,Value,DateModified,...)

在某些情况下,某个字段有多个值,但在我的查询中,我只希望每个字段有一个值(如果有)。

这是我的代码无法正常工作:

SELECT  f.FormID, f.FieldID, f.FormID, f.Title, v.Value, v.UserName FROM
(SELECT * FROM FormFields WHERE FormID = '2D6C42E1-0C95-4E40-B792-A17E00C001BF') AS f
LEFT JOIN
(select FormID, ItemID, FieldID, Value, UserName, DateModified from FormValues 
    where FormID = '2D6C42E1-0C95-4E40-B792-A17E00C001BF') as v
ON f.FormID = v.FormID AND f.FieldID = v.FieldID
ORDER BY f.SO

结果:

FormID                                  FieldID                                 Title       Value   UserName
2D6C42E1-0C95-4E40-B792-A17E00C001BF    E7A78AC7-10A4-4752-85D6-A17E00C22EF9    Field One   Val One User1
2D6C42E1-0C95-4E40-B792-A17E00C001BF    E7A78AC7-10A4-4752-85D6-A17E00C22EF9    Field One   Val Two User2
2D6C42E1-0C95-4E40-B792-A17E00C001BF    8E1FAC2A-02F1-4D0D-A3E0-A184001484D8    Field Two   NULL    NULL

注意:第二行是不需要的。

我试过“分组”,但没有为我工作。请有人帮助我。

提前致谢, Kardo

1 个答案:

答案 0 :(得分:1)

尝试

SELECT  f.FormID, f.FieldID, f.FormID, f.Title, v.Value, v.UserName FROM
(SELECT * FROM FormFields WHERE FormID = '2D6C42E1-0C95-4E40-B792-A17E00C001BF') AS f
LEFT JOIN
(select FormID, ItemID, FieldID, Value, UserName, DateModified,
ROW_NUMBER() OVER (PARTITION BY FieldID ORDER BY Value) as rn from FormValues 
    where FormID = '2D6C42E1-0C95-4E40-B792-A17E00C001BF') as v
ON f.FormID = v.FormID AND f.FieldID = v.FieldID AND v.rn=1
ORDER BY f.SO

您可能需要根据您希望成为该组中第一行的ORDER BY Value子句来调整OVER(“One”和“Two”它将返回“One”,但是我不知道其他可能的值。)