简单的sql字符串更正

时间:2012-12-13 17:07:36

标签: sql sqlite

我的sqlite3数据库中有2个表。有人可以帮我使用下面的sql命令:

tbltrans

transid |  transdate | discountpercentage | Bank
12345     10/09/2011     5                  20.00

tbltrans2

transid   |   itemnr   |price | btwpercentage | qty
12345         205        10.11        12        5
12345         302        15.00        6         7
12345         501        20.00        21        3

我的第一个问题是:

  1. 我想获得一张查询表,其中包含每笔transid和计算现金的总销售额,例如:

    Select
        Sum(tbltrans2.qty * tbltrans2.price) as TotalAmount,
        (Totalamount - tbltrans.Bank) as Cash
    where 
        tbltrans.transid = tbltrans2.transid 
        and transdate = '10/09/12'
    

    有人可以更正此SQL语句吗?

  2. - 以下问题已经解决 -

    所以,任何人都可以更正我的sql代码来使用这个表格布局:

    select 
        sum(price * qty - (price * qty) * (tbltrans.discountpercentage / 100)  
    from 
        tbltrans2 
    where 
        btwpercentage = 6) as total6 ,
      sum(price * qty - (price*qty)*(tbltrans.discountpercentage /100) from tbltrans2 where btwpercentage =12) as total12,
    sum(price * qty - (price*qty)*(tbltrans.discountpercentage /100) from tbltrans2 where btwpercentage =21) as total21
     where transdate = date('10/09/2011')
    

2 个答案:

答案 0 :(得分:1)

您应该能够加入表并使用以下内容:

select 
  sum(case when t2.btwpercentage =6 then
        t2.price * t2.qty - (t2.price * t2.qty* t1.discountpercentage /100) end) Total6,
  sum(case when t2.btwpercentage =12 then
        t2.price * t2.qty - (t2.price * t2.qty* t1.discountpercentage /100) end) Total12,
  sum(case when t2.btwpercentage =21 then
        t2.price * t2.qty - (t2.price * t2.qty* t1.discountpercentage /100) end) Total21
from tbltrans t1
left join tbltrans2 t2
  on t1.transid = t2.transid
where transdate = date('10/09/2011')

请参阅SQL Fiddle with Demo

根据您的评论,您还可以使用:

select count(t1.transid) Total,
  sum(case when t2.btwpercentage =6 then
        t2.price * t2.qty - (t2.price * t2.qty* t1.discountpercentage /100) end) Total6,
  sum(case when t2.btwpercentage =12 then
        t2.price * t2.qty - (t2.price * t2.qty* t1.discountpercentage /100) end) Total12,
  sum(case when t2.btwpercentage =21 then
        t2.price * t2.qty - (t2.price * t2.qty* t1.discountpercentage /100) end) Total21
from tbltrans t1
left join tbltrans2 t2
  on t1.transid = t2.transid
where transdate = date('10/09/2011')

答案 1 :(得分:1)

如果您希望查询基本上按照书面形式工作,那么您需要添加from子句:

Select 
sum(price * qty - (price*qty)*(tbltrans.discountpercentage /100) from tbltrans2 where btwpercentage =6) as total6 ,
 sum(price * qty - (price*qty)*(tbltrans.discountpercentage /100) from tbltrans2 where btwpercentage =12) as total12,
sum(price * qty - (price*qty)*(tbltrans.discountpercentage /100) from tbltrans2 where btwpercentage =21) as total21
from tbltrans
 where transdate = date('10/09/2011')

然而,bluefeet提供了一个更简洁的版本,虽然我会将选择逻辑写为:

sum(case when t2."btwpercentage" =6
         then  t2."price"*t2."qty" * (1 - t1."discountpercentage" /100.0)
     end) Total6,