如何使用Sql按此声明排序?

时间:2011-05-25 15:08:32

标签: sql sql-server-2008

如何按小部件数量订购列表'widgets_spec?

select distinct
     m.p_c_id
    ,(select distinct '<li>' +convert(varchar,widgets) + '<br> '
      from dbo.spec_master m2
          where m.p_c_id = m2.p_c_id and widgets is not null
          for xml path(''), type).value('.[1]', 'nvarchar(max)'
     ) as widgets_spec
from dbo.spec_master m
inner join dbo.ProductVaration pv on pv.p_c_id = m.p_c_id
inner join dbo.Varation v on v.varation_id = pv.varation_type_id
where v.varation_id  = 4
group by m.p_c_id

现在输出如下:

<li>10<br> <li>12<br> <li>15<br> <li>8<br>

当我希望它看起来像:

<li>8<br> <li>10<br> <li>12<br> <li>15<br> 

感谢您的帮助。

编辑:我正在尝试订购连接值的内部select语句。

3 个答案:

答案 0 :(得分:2)

您不需要DistinctGroup By。你应该使用其中一个。在这种情况下,我相信你必须使用Group By才能工作。

Select m.p_c_id
    , (
        Select '<li>' + Cast( m2.num_of_lights As varchar(10)) + '<br /> '
        From dbo.spec_master As m2
        Where m.p_c_id = m2.p_c_id 
            And m2.num_of_lights Is Not Null
        Group By m2.num_of_lights   
        Order By m2.num_of_lights
        For Xml Path(''), type).value('.[1]', 'nvarchar(max)'
        ) As numLights_spec
From dbo.spec_master As m
    Inner Join dbo.ProductVaration As pv 
        On pv.p_c_id = m.p_c_id
    Inner Join dbo.Varation As v 
        On v.varation_id = pv.varation_type_id
Where v.varation_id  = 4
Group by m.p_c_id

答案 1 :(得分:0)

  select distinct
     m.p_c_id
    ,(select distinct '<li>' +convert(varchar,num_of_lights) + '<br> '
      from dbo.spec_master m2
          where m.p_c_id = m2.p_c_id and num_of_lights is not null
      ORDER BY convert(varchar,num_of_lights)
     ) as numLights_spec
  from dbo.spec_master m
  inner join dbo.ProductVaration pv on pv.p_c_id = m.p_c_id
  inner join dbo.Varation v on v.varation_id = pv.varation_type_id
  where v.varation_id  = 4
  group by m.p_c_id
) As SubA

答案 2 :(得分:0)

这里的其他一些答案是行不通的,因为现在通过now-varchar num_of_lights排序会在'15'之后放'8',就像现在发生的那样。您想以数字方式订购numLights,这不会发生在它们周围的那些html标签上。您可以在子选择中添加子选择,以便您对它们进行排序,然后使用它们周围的标记选择它们。示例(未测试):

SELECT * FROM (
  select distinct
  m.p_c_id
 ,(select distinct '<li>' +convert(varchar,num_of_lights) + '<br> '
  from (select distinct p_c_id, num_of_lights from dbo.spec_master order by num_of_lights) m2
      where m.p_c_id = m2.p_c_id and num_of_lights is not null
      for xml path(''), type).value('.[1]', 'nvarchar(max)'
 ) as numLights_spec
from dbo.spec_master m
inner join dbo.ProductVaration pv on pv.p_c_id = m.p_c_id
inner join dbo.Varation v on v.varation_id = pv.varation_type_id
where v.varation_id  = 4
group by m.p_c_id

就个人而言,我只是在后端代码中添加html标签,以获取查询结果。