具有多个where子句和组的多选

时间:2016-05-11 05:02:28

标签: mysql sql

我正在尝试从mysql数据库中获取数据以生成报告。但是当我有多个where和group子句的多个选择时,我很挣扎。

我想要做的是我希望第二个和第三个select语句中的SUM(pf.meter)应该根据相关select语句中给出的where子句返回值,并且需要按主选择语句Group by子句进行分组。

enter image description here 请找到attachemnet.in没有计划的数量是相同的所有行,它不能像那样。它应该按客户,颜色,风格分组。

这是我的 SQL

SELECT  pm.date, 
        pm.customer, 
        pf.style, 
        pf.color, 
        COUNT(pf.roll_no) AS Roll_QTY,
        SUM(pf.yard) AS Yard_QTY, 
        SUM(pf.meter) AS Meter_QTY, 
        SUM(pf.kilo) AS Kilo_QTY, 
        (
            SELECT SUM(pf.meter)
            FROM packinglists_fabrics_items pf, packinglists_main pm
            WHERE pf.aql_status = 0
            AND pf.grn_no= pm.gp_no[
            AND pm.date BETWEEN {DateR, RANGE1} AND {DateR, RANGE2}]
        ) FB_Not_Passed_Qty,    
        (
            SELECT SUM(pf.meter)
            FROM packinglists_fabrics_items pf, packinglists_main pm
            WHERE pf.aql_status = 1
            AND pf.tag_gen = 0
            AND pf.grn_no= pm.gp_no[
            AND pm.date BETWEEN {DateR, RANGE1} AND {DateR, RANGE2}]
        ) Not_Planned_Qty
FROM packinglists_main pm, packinglists_fabrics_items pf
WHERE pf.grn_no= pm.gp_no[
AND pm.date BETWEEN {DateR, RANGE1} AND {DateR, RANGE2}]
GROUP BY pm.customer, pf.style, pf.color

2 个答案:

答案 0 :(得分:1)

SELECT pm.date, pm.customer, pf.style, pf.color, COUNT(pf.roll_no) AS Roll_QTY,
       SUM(pf.yard) AS Yard_QTY, SUM(pf.meter) AS Meter_QTY, SUM(pf.kilo) AS Kilo_QTY, 
    SUM( case when pf.aql_status = 0  then pf.meter else 0 end ) FB_Not_Passed_Qty,
    SUM( case when pf.aql_status = 1 and  pf.tag_gen = 0  then pf.meter else 0 end ) Not_Planned_Qty
FROM packinglists_main pm,
     packinglists_fabrics_items pf
WHERE pf.grn_no= pm.gp_no[
  AND pm.date BETWEEN {DateR,
                       RANGE1} AND {DateR,
                                    RANGE2}]
GROUP BY pm.customer, pf.style, pf.color

答案 1 :(得分:0)

目前尚不清楚你想要达到的目标;没有任何样本数据或预期输出的例子。

但看起来你可能会追随条件聚合的结果:

这样的结果:

SELECT pm.date
     , pm.customer
     , pf.style
     , pf.color
     , COUNT(pf.roll_no)    AS Roll_QTY
     , SUM(pf.yard)         AS Yard_QTY
     , SUM(pf.meter)        AS Meter_QTY
     , SUM(pf.kilo)         AS Kilo_QTY

     , SUM( IF(pf.aql_status = 0, pf.meter, 0) ) AS FB_Not_Passed_Qty

     , SUM( IF(pf.aql_status = 1 AND pf.tag_gen = 0, pf.meter, 0) ) AS Not_Planned_Qty

  FROM packinglists_main pm
  JOIN packinglists_fabrics_items pf
    ON pf.grn_no = pm.gp_no
 WHERE pm.date BETWEEN ? AND ?
 GROUP
    BY pm.customer
     , pf.style
     , pf.color

一些建议:

抛弃旧式逗号运算符以进行连接操作,并在ON子句中使用较新的JOIN语法和连接谓词。