3

我有一个存储过程

SELECT P.Name,P.Description,
      PP.Attribute,PD.Value
FROM admin.Profiles P
LEFT JOIN admin.ProfilePreferenceMap PPM on P.ProfileID=PPM.ProfileID
LEFT JOIN admin.ProfilePrefDtl PD on PD.ProfilePrefDtlID=PPM.PreferenceID
LEFT JOIN admin.ProfilePref PP on PP.ProfilePrefID=PD.ProfilePrefID
WHERE P.Name='Profile1'

它返回像

Name          Description           Attribute  Value
Profile1    Profile 1 description     E         EV
Profile1    Profile 1 description     S         SV

我想得到结果

Name            Description         Attribute   Value
Profile1    Profile 1 description   E,S         EV,SV

我的目的是将此值转换为 JSON 数据,例如 -

[{"Name":"Profile1","Description":"Profile 1 description","Attribute":["E", "S"],"Value":["EV", "SV"]}]
4

2 回答 2

2

您应该模拟 MySql 中存在的 GROUP_CONCAT()

SQLFiddle 演示

with t as
(
  SELECT P.Name,P.Description,
      PP.Attribute,PD.Value
  FROM admin.Profiles P
  LEFT JOIN admin.ProfilePreferenceMap PPM on P.ProfileID=PPM.ProfileID
  LEFT JOIN admin.ProfilePrefDtl PD on PD.ProfilePrefDtlID=PPM.PreferenceID
  LEFT JOIN admin.ProfilePref PP on PP.ProfilePrefID=PD.ProfilePrefID
  WHERE P.Name='Profile1'
)

select 
    Name,Description, 
    stuff((select ', ' + Attribute 
           from t t2 where t1.NAme = t2.NAme and t1.Description = t2.Description
           for xml path('')),
          1,2,'') [Attributes],
    stuff((select ', ' + Value
           from t t2 where t1.NAme = t2.NAme and t1.Description = t2.Description
           for xml path('')),
          1,2,'') [Values]
from t t1
group by Name,Description
于 2013-03-12T06:21:51.393 回答
0

您可以使用group by按唯一名称或描述列进行分组,但我不确定是否有一种简单的方法来获取逗号分隔值,由不同行中的值组成,除非您对Temp表格做了一些事情并且CONCAT()可能?

如果分组没问题,试试这个:

SELECT P.Name,P.Description,
      PP.Attribute,PD.Value
FROM admin.Profiles P
LEFT JOIN admin.ProfilePreferenceMap PPM on P.ProfileID=PPM.ProfileID
LEFT JOIN admin.ProfilePrefDtl PD on PD.ProfilePrefDtlID=PPM.PreferenceID
LEFT JOIN admin.ProfilePref PP on PP.ProfilePrefID=PD.ProfilePrefID
WHERE P.Name='Profile1'
GROUP BY P.Name

Attribute但是,像这样的分组只会显示您和Value列的第一行(基于排序)

于 2013-03-12T05:10:20.677 回答