查询返回两行

时间:2015-12-11 19:02:34

标签: sql-server tsql select case

我有一个表格,其中有一个名为type的列,其中包含值为发票或订单的值,然后是另一列保存该值以及包含客户编号等的列。

我写了一个剧本: -

select 
    customer, 
    (CASE WHEN TYPE = 'INVOICED' THEN SUM(INVTOTAL) else 0 END) AS INVTOTAL, 
    (CASE WHEN TYPE = 'ORDERS' THEN SUM(INVTOTAL) else 0 END) AS ORDERTOTAL
from 
    salestable

为什么会返回以下内容?

customer      INVTOTAL   ORDERTOTAL
Joe Bloggs   1000            0
Joe Bloggs     0          1300

而不是

customer      INVTOTAL   ORDERTOTAL
Joe Bloggs   1000            1300   

很抱歉问这样一个新手问题,但我是SQL新手并且正在学习它......

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

您的查询缺少group by。同时在sum周围使用case以避免多行。

select customer, 
       sum(CASE WHEN TYPE = 'INVOICED' THEN INVTOTAL else 0 END) AS INVTOTAL, 
       sum(CASE WHEN TYPE = 'ORDERS'   THEN INVTOTAL else 0 END) AS ORDERTOTAL
from salestable
group by customer

答案 1 :(得分:1)

你需要与顾客一起做一个避免多行的小组。检查下面的小提琴。

create table tb1
(customer varchar(25),
 type varchar(25),
 invoice numeric(18,2)
 );

 insert into tb1(customer,type,invoice) values('Joe Bloggs','INVOICED',1000);
 insert into tb1(customer,type,invoice) values('Joe Bloggs','ORDERS',1000);

select customer, 
sum(CASE WHEN TYPE = 'INVOICED' THEN  sum(invoice) else 0 END) AS INVTOTAL, 
sum(CASE WHEN TYPE = 'ORDERS'   THEN  sum(invoice) else 0 END) AS ORDERTOTAL
from tb1
group by customer

fiddle with example

您需要将整个案例陈述放在sum()中 为了避免type分组,你也会得到以下错误

    Column 'tb1.type' is invalid in the select list because it is 
not contained in either an aggregate function or the GROUP BY clause.

答案 2 :(得分:0)

因为select会为匹配where过滤器的表中的每一行返回一行。如果没有过滤器,那么表中每行的结果行。如果您想“加入”行,您可以尝试按客户分组,例如:

SELECT customer,
       SUM(CASE WHEN TYPE = 'INVOICED' THEN INVTOTAL ELSE 0 END) as INVTOTAL,
       SUM(CASE WHEN TYPE = 'ORDERS'   THEN INVTOTAL ELSE 0 END) as ORDERTOTAL
FROM salestable
GROUP BY customer