多个记录时如何返回特定文本

时间:2018-12-19 21:20:42

标签: sql

我对SQL比较陌生,因此我将尝试使术语正确。我有2个表,tbl_Trans保存常规交易明细,tbl_TransData保存交易明细。

我想显示每个Trans记录和tbl_TransData中保存的trans的类别。如果每个Trans都有多个类别,我希望文本为“ Mulitple”,否则返回类别字段

TRANS表内容

int_Trans_ID    dtm_TransDate   txt_Type    txt_Description txt_Bank dbl_Amount
1               17/12/2018      REC         Sales           Current 1000
2               20/12/2018      PAY         Expenses paid   Current -155
3               21/12/2018      PAY         MW Repairs      Current -250

TRANSDATA表内容

int_TransData_ID    int_TransID txt_Category    dbl_Amount
1                   1           Sales A         -600
2                   1           Sales B         -400
3                   2           Travel          100
4                   2           Meal            55
5                   3           MW Repairs      250

到目前为止,这是代码,但是如果我将ELSE'Single'替换为ELSE txt_Category,则无法使用。

SELECT
int_Trans_ID,
dtm_TransDate AS Date,
txt_Type AS Type,
txt_Description AS Description,
    (SELECT 
            CASE
                WHEN count(int_TransID) > 1
                THEN 'Multiple'
                ELSE 'Single'
            END
    FROM
        dbo.tbl_TransData TD
    WHERE
        TD.int_TransID = T.int_Trans_ID) AS Category
FROM
   tbl_Trans T
GROUP BY
   int_Trans_ID, dtm_TransDate, txt_Type, txt_Description

这就是我想看到的。

int_Trans_ID    Date        Type    Description   Category
1               2018-12-17  REC     Sales         Multiple
2               2018-12-20  PAY     Expenses paid Multiple
3               2018-12-21  PAY     Car Repairs   MW Repairs

对不起,表格的格式。

任何帮助,甚至指向其他职位的方向,都将不胜感激。

2 个答案:

答案 0 :(得分:2)

我会做的:

with
x as (
  select ins_trans_id, count(*) as cnt, max(txt_category) as cat 
  from transdata
  group by ins_trans_id
)
select
  t.int_trans_id,
  t.dtm_transdate,
  t.txt_type,
  t.txt_description,
  case when x.cnt = 0 then 'no category'
       when x.cnt = 1 then x.cat
       else 'Multiple' end as Category
from trans t
left join x on x.int_trans_id = t.int_trans_id

答案 1 :(得分:1)

请看看这个, 我写了子查询来满足条件

SELECT
  int_Trans_ID,
  dtm_TransDate,
  txt_type,
  txt_Description,
  CASE WHEN (SELECT COUNT(*) FROM tbl_Trans_Data td WHERE td.int_Trans_ID = t.int_Trans_ID)) > 1 THEN
    'MULTİPLE'
  ELSE 
    (SELECT Category from tbl_trans_data td Where td.int_Trans_ID = t.int_Trans_ID)
  END AS Category
FROM
  tbl_Trans t