如何在一个选择中获取行和组?

时间:2013-09-26 01:44:28

标签: sql sql-server sql-server-2008

代码:

SELECT ta.name AS ta_name,
       ta.unit  AS ta_unit,
       ta.id_producer_goods AS ta_id_producer_goods
    FROM   Table ta
    WHERE  id_city = '24'
           AND id_firm = '22131'
           AND id_service = '5'

在select me中,需要按ta_name获取包含行的行(结果应仅包含唯一的ta_name)并获取所有表中每个唯一ta_name的计数。

怎么做?

2 个答案:

答案 0 :(得分:1)

似乎太简单了 - 但这就是我理解你需要的东西。

SELECT ta.name AS ta_name,
  ta.unit              AS ta_unit,
  ta.id_producer_goods AS ta_id_producer_goods, COUNT(*)
FROM TABLE ta
WHERE id_city  = '24'
AND id_firm    = '22131'
AND id_service = '5'
GROUP BY ta.name, ta.unit, ta.id_producer_goods

答案 1 :(得分:0)

我认为这可能会有所帮助

SELECT DISTINCT COUNT(ta.name)
            ,   ta.name AS ta_name
            ,   ta.unit AS ta_unit
            ,   ta.id_producer_goods AS
                ta_id_producer_goods
FROM [table] ta
WHERE id_city = '24'
    AND id_firm = '22131'
    AND id_service = '5'
GROUP BY
        ta.name
    ,   ta.unit
    ,   ta.id_producer_goods