MySQL Count基于文本词

时间:2018-01-03 16:25:21

标签: mysql sql mysql-workbench

我正在研究SKU的数量(基于每个SKU),因为我知道SKU' H-ROOT-C'已退款3项。

SELECT 
    sku,
    count(IF(transaction_type = 'Refund'AND amount_description = 'Principal' AND amount_type = 'ItemPrice', sku, 0)) AS 'refund_QTY_Order'
FROM
    settlements_qty_test
WHERE
    (sku NOT LIKE '%loc%'
        AND sku NOT LIKE 'isc%'
        AND sku NOT LIKE 'trek%')
GROUP BY SKU ='H-ROOT-C'
HAVING sku IS NOT NULL AND LENGTH(sku) > 0
ORDER BY refund_QTY_Order ASC

结果输出

'H-ROOT-C', '125'

我保持所有退款的结果为125,因为我希望这个搜索重点放在每组SKU上,而h-root-C应该是3项返回,而不是125项返回。我不想要所有SKU退款,我想要这个SKU =' H-root-c'仅

2 个答案:

答案 0 :(得分:1)

试试这个:

    SELECT 
    sku,
    count(sku) AS 'refund_QTY_Order'
FROM
    settlements_qty_test
WHERE (sku NOT LIKE '%loc%' AND sku NOT LIKE 'isc%' 
AND sku NOT LIKE 'trek%' 
AND sku IS NOT NULL AND LENGTH(sku) > 0 
AND transaction_type = 'Refund'AND amount_description = 'Principal' 
AND amount_type = 'ItemPrice')
GROUP BY SKU ORDER BY refund_QTY_Order ASC
  

如果你想要的是只有那个有'sk-H-ROOT-C'的记录:

    SELECT 
        sku,
        count(sku) AS 'refund_QTY_Order'
    FROM
        settlements_qty_test
    WHERE (sku IS NOT NULL AND sku='H-ROOT-C' 
    AND transaction_type = 'Refund'AND amount_description = 'Principal' 
    AND amount_type = 'ItemPrice')
    GROUP BY SKU ORDER BY refund_QTY_Order ASC

答案 1 :(得分:1)

您可以将其简化为:

SELECT sku
       sum( (transaction_type = 'Refund' AND
             amount_description = 'Principal' AND
             amount_type = 'ItemPrice'
            )
           ) AS refund_QTY_Order
FROM settlements_qty_test
WHERE sku NOT LIKE '%loc%' AND
      sku NOT LIKE 'isc%' AND
      sku NOT LIKE 'trek%' AND
      LENGTH(sku) > 0
GROUP BY SKU
ORDER BY refund_QTY_Order ASC;

NULL的比较是多余的。我在SELECT中保留了条件逻辑,因此您将获得0个值。