iT邦幫忙

0

SQL指令 如何寫?

sql
XYZ 2019-12-11 18:01:591566 瀏覽
  • 分享至 

  • xImage

請問
圖一 若B欄位是1 那麼希望下圖二C欄位是A欄位的值也就是12,
圖一 若B欄位不是1 那麼希望下圖二C欄位是A欄位的值-B欄位的值也就是3,
希望結果成呈現像圖二,該如何下SQL?

https://ithelp.ithome.com.tw/upload/images/20191211/201081576VPBo006BS.jpg

https://ithelp.ithome.com.tw/upload/images/20191211/20108157SZsGDZbqDY.jpg

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

3
海綿寶寶
iT邦大神 1 級 ‧ 2019-12-11 18:31:29
最佳解答

選我最佳解答

SELECT A,B,
  CASE WHEN B=1 THEN A
      ELSE A-B
      END AS C
FROM tblMain
CREATE TABLE tblMain
    (`A` int, `B` int)
;
    
INSERT INTO tblMain
    (`A`, `B`)
VALUES
    (12, 1),
    (14, 11)
;
XYZ iT邦新手 4 級 ‧ 2019-12-11 23:17:02 檢舉

Case when ,的when可以下2個條件嗎?我用SELECT A,B,
CASE WHEN B=1 and a >0 THEN A
ELSE A-B
END AS C
FROM tblMain

為何不行?

你那邊怎樣·我這邊OK

https://ithelp.ithome.com.tw/upload/images/20191212/200017872Svh62Ti2g.png

5
一級屠豬士
iT邦大師 1 級 ‧ 2019-12-11 23:40:10

不要選我最佳解答喔.不要害我喔...

create table itx191211 (
  id smallint generated always as identity
, a smallint not null
, b smallint not null
);

insert into itx191211 (a, b) values
(12, 1),
(14, 11);

select a
     , b
     , case
         when b = 1 and a > 0 then a
         else a - b
       end as c
  from itx191211;

+----+----+----+
| a  | b  | c  |
+----+----+----+
| 12 |  1 | 12 |
| 14 | 11 |  3 |
+----+----+----+
(2 rows)

-- 不用case 的方法

select a
     , b
     , a as c
  from itx191211
 where b = 1 and a > 0
 union all
select a
     , b
     , a - b as c
  from itx191211
 where not (b = 1 and a > 0);

+----+----+----+
| a  | b  | c  |
+----+----+----+
| 12 |  1 | 12 |
| 14 | 11 |  3 |
+----+----+----+
(2 rows)

哪一種速度會比較快呢?

我要發表回答

立即登入回答