我是SQL的新手,我正试图从数据库中提取一些数据。
我有两张桌子,一张名为'tblorders',另一张叫'tblorderitems',我希望将这些表格加入团队订购的物品数量。
这是我创建的查询:
SELECT fldcustomerid, fldname, fldcontactname, fldemail, SUM(fldqtyorder) as QtyOrdered
FROM tblorders AS A
INNER JOIN tblorderitems AS B ON A.fldorderid = B.fldorderid
WHERE fldstockcode LIKE 'TO%' AND fldorderdate BETWEEN '2014-01-01' AND '2016-12-31'
AND fldemail LIKE '%@%' AND fldqtyorder>=30
GROUP BY fldname, fldcustomerid, fldcontactname, fldemail
ORDER BY QtyOrdered DESC
我希望它能够将'fldqtyorder'列中的项目数相加,然后过滤结果,以便只显示超过30个项目的结果。
例如,初始表将是:
fldname: fldqtyorder: fldcontactname: fldemail:
TeamFC 24 Fred Jones email@email1.com
FootyFC 1 Steve Low Steeve@footy.com
TeamFC 16 James Wild James@bt.com
Palm FC 33 Phil Bate PBate@blah.com
最终结果应如下:
fldname: fldtotalqtyorder: fldcontactname: fldemail:
TeamFC 40 Fred Jones email@email1.com
Palm FC 33 Phil Bate PBate@blah.com
答案 0 :(得分:1)
你想:
SELECT fldcustomerid, fldname, fldcontactname, fldemail, SUM(fldqtyorder) as QtyOrdered
FROM tblorders AS A
INNER JOIN tblorderitems AS B ON A.fldorderid = B.fldorderid
WHERE fldstockcode LIKE 'TO%' AND fldorderdate BETWEEN '2014-01-01' AND '2016-12-31'
AND fldemail LIKE '%@%'
GROUP BY fldname
HAVING QtyOrdered >= 30
ORDER BY QtyOrdered DESC
对于相同的fldname,您有不同的fldcontactnames,因此它将随机选择一个用于输出。与fldemail和fldcustomerid相同。但除此之外,输出应该是您正在寻找的。 p>
您不能将额外的字段抛出到group by子句中,因为这会将组拆分为具有这些字段的唯一组合的每一行。如果您希望行具有相同的fldname时折叠为一行,则只有fldname可以在group by子句中。
答案 1 :(得分:0)
这是一个操作问题的命令。
在where子句被评估时,它仅记录在单个记录上。通过将总和的评估移动到having子句,引擎将评估聚合并仅返回那些> = 30。
简单地从中删除> = 30并将其放入(不需要子查询)
SELECT fldcustomerid
, fldname
, fldcontactname
, fldemail
, SUM(fldqtyorder) as QtyOrdered
FROM tblorders AS A
INNER JOIN tblorderitems AS B
ON A.fldorderid = B.fldorderid
WHERE fldstockcode LIKE 'TO%'
AND fldorderdate BETWEEN '2014-01-01' AND '2016-12-31'
AND fldemail LIKE '%@%'
GROUP BY fldname, fldcustomerid, fldcontactname, fldemail
HAVING sum(fldqtyorder)>=30
ORDER BY QtyOrdered DESC