如何在sql中获取计数行?

时间:2013-10-03 13:39:38

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

美好的一天。

结构表here

带有foreignt键的原始结构表(无法添加到sqlfiddle中)here

代码:

SELECT 
    COUNT(*) as count 
FROM Price p 
    left join Firm f on f.id_service = p.id_service 
              AND f.id_city = p.id_city AND f.id_firm = p.id_firm 
    left join City city on city.id_city = p.id_city 
    left join Producer_country pc on pc.id_producer_country = p.id_producer_country 
    left join Dogovor d on d.id_service=p.id_service 
              AND d.id_city=p.id_city AND d.id_firm=p.id_firm 
WHERE 
    p.id_city='73041' AND p.include='1' 
    AND p.blocked='0' AND f.blocked='0' 
    AND f.dogovor='1' AND d.end_date >= '20131003 17:10:30' 
    AND (p.name LIKE 'test%' COLLATE SQL_Latin1_General_Cp1251_CI_AS) 
GROUP BY 
    p.id_price, 
    p.id_service, 
    p.name, 
    p.name_original, 
    p.id_producer_country, 
    p.id_firm, 
    f.name, 
    f.address, 
    f.phone, 
    city.name, 
    pc.name

我想获得计数行,但结果我得到下一个:

1

如果我在count中使用列名,例如代码:

SELECT 
    COUNT(p.id_price) as count 

我得到相同的结果......

任何人都知道如何计算所有行?

P.S。:结果我需要计算唯一的行数

p.name, 
p.name_original, 
p.id_producer_country, 
p.id_firm, 
f.name, 
f.address, 
f.phone, 
city.name, 
pc.name

2 个答案:

答案 0 :(得分:3)

只需删除GROUP BY

即可
SELECT 
    COUNT(*) as count 
FROM Price p 
left join Firm f on f.id_service = p.id_service 
            AND f.id_city = p.id_city AND f.id_firm = p.id_firm 
left join City city on city.id_city = p.id_city 
left join Producer_country pc on pc.id_producer_country = p.id_producer_country 
left join Dogovor d on d.id_service=p.id_service 
              AND d.id_city=p.id_city AND d.id_firm=p.id_firm 
WHERE 
    p.id_city='73041' AND p.include='1' 
    AND p.blocked='0' AND f.blocked='0' 
    AND f.dogovor='1' AND d.end_date >= '20131003 17:10:30' 
    AND (p.name LIKE 'test%' COLLATE SQL_Latin1_General_Cp1251_CI_AS);

如果您希望结果集中的每一行都作为一个组使用GROUP BY,并在GROUP BY中指定的一列或多列中表示一个或多个具有相同值的行。但在你的情况下,你想要所有行的计数,所以没有必要。

答案 1 :(得分:0)

而不是使用COUNT(*),而是使用任何联接表中所需的唯一字段名称来获取单数