HORTING + GROUP BY中的COUNT

时间:2017-02-03 07:13:50

标签: mysql sql database

我正在尝试构建一个查询,该查询仅捕获数据库中有多个制造商条形码的SKU(产品)。 我试图使用变量,但它不起作用

Table 1 (wms_inventory)
SKU1
SKU2
SKU3

_

Table 2 (ims_manufacturer_barcode)
SKU1 MB1
SKU1 MB2
SKU2 MB3
SKU3 MB4
SKU3 MB5
SKU3 MB6

_

Result expected
SKU1 | 2
SKU3 | 3

-> no SKU2 in the results because there is only 1 Manufacturer Barcode.

_

SELECT
i.fk_current_warehouse AS `Warehouse`,
i.sku AS `SKU`,
@var := COUNT(DISTINCT b.manufacturer_barcode) AS `Number of different Manufacturer Barcode`
FROM wms_inventory i
LEFT JOIN ims_manufacturer_barcode b ON i.sku = b.sku
HAVING @var > 1
GROUP BY i.sku
;

_

以上查询引发以下错误

SQL Error (1064): You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version
for the right syntax to use near 'GROUP BY i.sku' at line 8

4 个答案:

答案 0 :(得分:1)

您可以尝试以下查询。

SELECT t2.SKU, COUNT(*) total
  FROM Table1 t1, Table2 t2
WHERE t1.SKU = t2.SKU 
 GROUP BY t2.SKU
HAVING COUNT(*) > 1

答案 1 :(得分:1)

以下查询将帮助您......

class CommentForm(forms.ModelForm):  
    class Meta:
        model = Comment
        widgets = {
            'body': forms.Textarea(attrs={'cols': 80, 'rows': 20})
        }

答案 2 :(得分:0)

尝试以下操作:在内部查询中,准备具有多个制造商的SKU。外部查询然后获取所有记录,其中SKU是内部查询的记录之一:

select * from table2 result
where result.SKU in
  (select sku
   from table2 cnt
   group by cnt.sku
   having count(*) > 1)

答案 3 :(得分:0)

SELECT my_column, COUNT(*) total
  FROM table2 
 GROUP BY my_column
HAVING COUNT(*) > 1  -- if distinct is required then you probably have bigger design problems