关于求和量的Mysql查询

时间:2015-12-03 12:41:38

标签: mysql

SELECT a. id,
       a.kataloski_broj, 
       SUM(a.quantity) AS zbroj, 
       entry_type_desc, 
       posting_date, 
       item_category, 
       product_group,
       b.nabavna_cijena as neto_nabavna,
       b.neto_VPC,
       b.preporucena_VPC,
       c.nabavna_cijena as rabat_nabavna,
       c.VPC,
       d.VPC as NAV_VPC,
       d.PVPC as NAV_PVPC
    FROM prodaja_zaliha a
  LEFT JOIN kalkulacija_stavke b ON a.kataloski_broj = b.kataloski_broj
  LEFT JOIN kalkulacija_stavke_rabat c ON a.kataloski_broj = c.kataloski_broj
  LEFT JOIN katalog_pribora_item d ON a.kataloski_broj = d.kataloski_broj_NAV
    WHERE a.entry_type_desc = 'Prodaja' 
    AND YEAR(a.posting_date) = '2015' 
    AND a.kataloski_broj = 'M1200'
  GROUP BY a.id ASC

为什么此查询未返回正确的值? SUM(a.quantity)AS zbroj返回1432而不是182行。这有什么不对?

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助

SELECT a. id,
           a.kataloski_broj, 
        e.zbroj  as zbroj, 
           entry_type_desc, 
           posting_date, 
           item_category, 
           product_group,
           b.nabavna_cijena as neto_nabavna,
           b.neto_VPC,
           b.preporucena_VPC,
           c.nabavna_cijena as rabat_nabavna,
           c.VPC,
           d.VPC as NAV_VPC,
           d.PVPC as NAV_PVPC
        FROM prodaja_zaliha a
    inner JOIN (select id, SUM(quantity) AS zbroj  FROM prodaja_zaliha  WHERE entry_type_desc = 'Prodaja' 
        AND YEAR(posting_date) = '2015' 
        AND kataloski_broj = 'M1200') as e on e.id=a.id
      LEFT JOIN kalkulacija_stavke b ON a.kataloski_broj = b.kataloski_broj
      LEFT JOIN kalkulacija_stavke_rabat c ON a.kataloski_broj = c.kataloski_broj
      LEFT JOIN katalog_pribora_item d ON a.kataloski_broj = d.kataloski_broj_NAV
        WHERE a.entry_type_desc = 'Prodaja' 
        AND YEAR(a.posting_date) = '2015' 
        AND a.kataloski_broj = 'M1200'
        GROUP BY a.id
        ORDER BY a.id DESC

答案 1 :(得分:0)

SELECT ABS(SUM(quantity)) as zbroj, a.kataloski_broj, a.id, a.entry_type_desc, a.posting_date, a.item_category, a.product_group
  FROM prodaja_zaliha a
  LEFT JOIN (SELECT kataloski_broj, nabavna_cijena, neto_VPC, preporucena_VPC
  FROM kalkulacija_stavke
  GROUP BY kataloski_broj) AS b
  ON a.kataloski_broj = b.kataloski_broj
  LEFT JOIN (SELECT kataloski_broj, nabavna_cijena, VPC
    FROM kalkulacija_stavke_rabat
    GROUP BY kataloski_broj) AS c
  ON a.kataloski_broj = c.kataloski_broj
  LEFT JOIN(SELECT kataloski_broj_NAV, VPC, PVPC
    FROM katalog_pribora_item
    GROUP BY kataloski_broj_NAV) AS d
  ON a.kataloski_broj = d.kataloski_broj_NAV
WHERE a.kataloski_broj = 'M1200' AND
  a.entry_type_desc = 'Prodaja' AND
YEAR(a.posting_date) = '2015'

这是返回正确结果的查询!