【问题标题】:Query returns two lines查询返回两行
【发布时间】:2016-03-17 18:58:15
【问题描述】:

我有一个表,其中有一个名为 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 新手,正在学习它...

感谢您的帮助!

【问题讨论】:

  • 很明显是salestable中的两行

标签: sql-server tsql select case


【解决方案1】:

您的查询缺少group by。还要在case 周围使用sum 以避免出现多行。

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

【讨论】:

    【解决方案2】:

    因为 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
    

    【讨论】:

    • 没有订单总数
    • 哎呀,对。只是在看最终结果表
    【解决方案3】:

    您需要与客户进行分组以避免多行。检查下面的小提琴。

    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

    你需要将整个 case 语句放入 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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多