MySQL在select中计算类似的行

时间:2013-11-11 07:43:27

标签: mysql sql

我有这个问题:

SELECT organisation.organisation as org, kund_nr as kundnrnr
FROM anv_data
INNER JOIN organisation ON organisation.ID = anv_data.organisation_id
INNER JOIN anvandare ON anv_data.anvandare_id = anvandare.ID
WHERE anv_data.indatum<='2013-10-31' AND anv_data.indatum>='2013-10-01' AND anv_data.rp = '0'
GROUP BY MONTH(anv_data.indatum), anv_data.anvandare_id ORDER BY anvandare.anstallningsnr

生成此响应:

organisation    kundnr
---------------------------
Företag1        123456
Företag1        123456
Företag1        123456
Företag2        789123
Företag2        789123
Företag2        789123
Företag2        789123

我想修改查询,以便总结具有类似“组织”的行,所以它看起来像:

organisation    kundnr  sum
---------------------------
Företag1        123456  3
Företag2        789123  4

这可能吗?

2 个答案:

答案 0 :(得分:0)

SELECT A.org,A.kundnrnr,count(1) as sum
FROM(
    SELECT organisation.organisation as org, kund_nr as kundnrnr
    FROM anv_data
    INNER JOIN organisation ON organisation.ID = anv_data.organisation_id
    INNER JOIN anvandare ON anv_data.anvandare_id = anvandare.ID
    WHERE anv_data.indatum<='2013-10-31' AND anv_data.indatum>='2013-10-01' AND anv_data.rp = '0'
    GROUP BY MONTH(anv_data.indatum), anv_data.anvandare_id ORDER BY anvandare.anstallningsnr
     ) A
GROUP BY A.org,A.kundnrnr

答案 1 :(得分:0)

尝试:

 SELECT organisation.organisation as org, kund_nr as kundnrnr, COUNT(*) sum
 FROM anv_data
 INNER JOIN organisation ON organisation.ID = anv_data.organisation_id
 INNER JOIN anvandare ON anv_data.anvandare_id = anvandare.ID
 WHERE anv_data.indatum<='2013-10-31' AND anv_data.indatum>='2013-10-01' AND anv_data.rp = '0'
 GROUP BY organisation.organisation, kund_nr
 ORDER BY organisation.organisation