【问题标题】:SQL - How to show in one row the same field with different values from 2 rowsSQL - 如何在一行中显示具有来自 2 行的不同值的相同字段
【发布时间】:2017-11-22 08:22:44
【问题描述】:

我有一个带有特定“where”子句的选择,其中有 2 行,但我需要在一行中显示这 2 个值但具有不同的“名称”

select 
case when t_docn <> 0 then t_docd end as doc_date,
case when t_docn = 0 then t_docd end as pay_date
from
ttfacr200606

where
t_ninv = '40000122'
and
t_ccur = 'BRL'

我得到这个代码

doc_date    pay_date
NULL    2015-08-21 00:00:00.000
2015-09-18 00:00:00.000 NULL

我需要

doc_date    pay_date
2015-09-18 00:00:00.000 2015-08-21 00:00:00.000

谢谢大家!

【问题讨论】:

  • 定义记录之间的共同点的字段是什么?包含实际数据以及查询结果是值得的
  • 你可以使用Outer Apply来做

标签: sql case union


【解决方案1】:

您可以使用聚合函数来执行此操作,但您需要验证它是否适合您拥有的所有情况。会是这样的:

select 
       t_ninv, 
       max(case when t_docn <> 0 then t_docd else null end) as doc_date,
       max(case when t_docn = 0 then t_docd else null end) as pay_date
  from ttfacr200606
 where t_ccur = 'BRL'
   and t_ninv = '40000122'
 group by t_ninv;

请注意,我使用列作为 cmets 中所说的公共点,因为如果您不使用它并且行数很多,则查询结果可能无法预测。

【讨论】:

  • 您好 Jorge,谢谢您的提示,但是当我执行您的代码时,它说:Msg 195, Level 15, State 10, Line 3 'max' is not a known built-in function name .
  • 你的数据库是什么?
  • sql server 11.0.2100 它来自我们的 ERP 数据库,我正在编写报告
  • OOOhhhh 抱歉实际上是错误的,我复制了您的查询并忘记删除别名
  • 天哪,人..它工作..谢谢!这是我第一次就堆栈溢出提出问题。有一段时间我只使用了一个研究数据库,谢谢顺便说一句!我会注意这个提示......我的问题是针对一个非常具体的案例,但我的报告更大,所以我现在将尝试看看它如何处理大量数据。谢谢!!!!
猜你喜欢
  • 2013-10-11
  • 1970-01-01
  • 2013-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多