-1

我的 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 语句吗?

-- 下面这个问题已经解决了 --

那么,任何人都可以更正我的 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')
4

2 回答 2

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

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

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')
于 2012-12-13T17:18:01.600 回答
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,
于 2012-12-13T17:40:59.657 回答