UNION查询中的“附近的错误”

时间:2013-07-11 12:05:42

标签: sql sqlite

我在SQLite中收到错误“FROM”附近的错误,但我在此查询中找不到任何错误。我做错了什么?

Select
tbltrans2_temp.itemcode,
tbltrans2_temp.itemname,
  Sum(tbltrans2_temp.qty) qty
From 
  tbltrans_temp Inner Join
  tbltrans2_temp On tbltrans2_temp.transID = tbltrans_temp.transid
 where
  tbltrans_temp.saleDate='11/07/2013'
Group By
  tbltrans2_temp.itemcode
  UNION
  Select
  tbltrans2.itemcode,
  tbltrans2.itemname,
  Sum(tbltrans2.qty) qty,
From 
  tbltrans Inner Join
  tbltrans2 On tbltrans2.transid = tbltrans.transid
   where
  tbltrans.saleDate='11/07/2013'
Group By
  tbltrans2.itemcode

1 个答案:

答案 0 :(得分:5)

在第二个,删除它之前还有一个FROM

Select
tbltrans2_temp.itemcode,
tbltrans2_temp.itemname,
  Sum(tbltrans2_temp.qty) qty
From 
  tbltrans_temp Inner Join
  tbltrans2_temp On tbltrans2_temp.transID = tbltrans_temp.transid
 where
  tbltrans_temp.saleDate='11/07/2013'
Group By
  tbltrans2_temp.itemcode
  UNION
  Select
  tbltrans2.itemcode,
  tbltrans2.itemname,
  Sum(tbltrans2.qty) qty,    <<<<-------------------  This
From 
  tbltrans Inner Join
  tbltrans2 On tbltrans2.transid = tbltrans.transid
   where
  tbltrans.saleDate='11/07/2013'
Group By
  tbltrans2.itemcode

更新

要从表中获取qty的总和,将该查询放在子查询中并将其加到外部查询中,您还可以省略内部查询中的sum并仅执行此操作在外面:

SELECT 
  itemcode,
  itemname,
  SUM(qty) TotalQty
FROM
(

    Select
    tbltrans2_temp.itemcode,
    tbltrans2_temp.itemname,
      Sum(tbltrans2_temp.qty) qty
    From 
      tbltrans_temp Inner Join
      tbltrans2_temp On tbltrans2_temp.transID = tbltrans_temp.transid
     where
      tbltrans_temp.saleDate='11/07/2013'
    Group By
      tbltrans2_temp.itemcode
      UNION
      Select
      tbltrans2.itemcode,
      tbltrans2.itemname,
      Sum(tbltrans2.qty) qty
    From 
      tbltrans Inner Join
      tbltrans2 On tbltrans2.transid = tbltrans.transid
       where
      tbltrans.saleDate='11/07/2013'
    Group By
      tbltrans2.itemcode
) t
GROUP BY itemcode, itemname;