sql查询以付款方式为条件进行销售总额

时间:2019-06-27 08:48:10

标签: sql sql-server

我想获取有条件的当日销售报告的金额

现金和卡之类的付款方式应分组为一行,其他付款为新行

swapChainPanel
CREATE TABLE IF NOT EXISTS `sale` (
  `ID` int(6) unsigned NOT NULL,
  `payment_method` int(3) unsigned NOT NULL,
  `amount` varchar(200) NOT NULL,
  `qty` varchar(200) NOT NULL,
 )

INSERT INTO `sale` (`id`, `payment_method`, `amount`,  `qty `) VALUES

  ('2', '200', '10050','1'),
  ('3', '201', '10050','1'),
  ('4', '200', '9045','1'),
  ('6', '227', '10050','1'),
  ('8', '228', '20050','2')

我知道,如果我按付款方式分组,则每种付款方式都会有一行,但是我不知道如何添加或将付款方式200和201分组为1种方式。

请帮助我将这两种付款的销售添加为一种。

我的期望值低于

select   payment_method,sum( amount),
sum(qty) from sale
group by payment_method

6 个答案:

答案 0 :(得分:2)

您可以将case表达式与group by一起使用:

select (case when payment_method in (200, 201) then 'cash' else 'credit' end),  -- or whatever values are appropriate
       sum( amount),
       sum(qty)
from sale
group by (case when payment_method in (200, 201) then 'cash' else 'credit' end);

请注意,尽管我认为应该在结果中,但不要在结果中包括第一列。如果不需要,可以删除select中的第一个表达式。

不过,实际上,您应该有一个payment_methods引用表并使用join

select pm.grouping,
       sum(s.amount),
       sum(s.qty)
from sale s join
     payment_methods pm
     on s.payment_method = pm.payment_method
group by pm.grouping;

定制逻辑(例如,不同付款方式的相似性)应存储在参考表中,而不是在不同查询中重复。后者是一场维护噩梦。

答案 1 :(得分:1)

您应该考虑将 Amount Qty 的数据类型分别更改为doc._idproplists:get_value(<<"_id">>, Doc)。以下查询应做您想要的

Numeric

答案 2 :(得分:1)

  select sum(amount),sum(qty) from sale
  where payment_method in (200,201)

  union all 

  select sum(amount),sum(qty) from sale
  where payment_method not in (200,201)

答案 3 :(得分:1)

以下查询将为您提供所需的结果-

 ;With cte (payment_method, amount, qty, category)as
 (
    select payment_method, amount,qty,
    case when payment_method in (200, 201) then 'cash&card' else 'Other' end as Category
    From sale
)
select Category, 
Sum(amount) Amount, Sum(qty) Quantity 
from cte 
group by category 

答案 4 :(得分:1)

SELECT COUNT(*),SUM(cast(t.amount as INT)) 
FROM (
    SELECT *,CASE WHEN [sale].payment_method in (200,201) THEN 1 ELSE 2 END Pt
FROM [sale]) t
GROUP BY t.Pt

答案 5 :(得分:1)

通过下面的查询来获取与您可以轻松实现的付款方式的差异。

select sum(cast(amount as int)),sum(cast(qty as int)),pmcalc 
from 
   (select id,payment_method,amount,qty,payment_method/10 as pmcalc from sale) r
group by pmcalc