计算 SQL 中的嵌套大小写
Count Nested Case in SQL
我想用 id_user 和 id_train 显示行序列
我可以在计数函数中嵌套 case 语句吗 sql?
我的 SQL 在这里,但它出错了
SELECT ticket.*
, COUNT( CASE trans.id_user WHEN 1 THEN 1
CASE trans.id_train WHEN 1 THEN 1
ELSE NULL END) AS total_ticket
, SUM(train.price) AS total_price
, user.*
FROM train JOIN trans ON trans.id_train = kereta.id_train
JOIN user ON trans.id_user = user.id_user
JOIN ticket ON ticket.train = train.id_train;
你可以这样做:
select COUNT( CASE trans.id_user WHEN 1
THEN 1
ELSE NULL
END) first_cnt
, COUNT( CASE trans.id_train WHEN 1
THEN 1
ELSE NULL
END) second_cnt
from trans;
但是,如果您想向 select 添加任何其他列,则需要按该列进行分组:
select trans.some_column
, COUNT( CASE trans.id_user WHEN 1
THEN 1
ELSE NULL
END) first_cnt
, COUNT( CASE trans.id_train WHEN 1
THEN 1
ELSE NULL
END) second_cnt
from trans
group by trans.some_column;
在您的情况下,这意味着您需要按票证中的所有列进行分组,因为您使用此:ticket.*
,用户中的所有列,因为您使用 user.*
另请注意,以上所有内容均可应用于您的 select 中的 SUM
。
COUNT( CASE trans.id_user WHEN 1 THEN 1
CASE trans.id_train WHEN 1 THEN 1
ELSE NULL END ) AS total_ticket
结构不明确。看起来您需要以下变体之一。
COUNT( CASE WHEN trans.id_user = 1 THEN 1
WHEN trans.id_train = 1 THEN 1
ELSE NULL END ) AS total_ticket
-- which may be simplified to
SUM(1 IN (trans.id_user, trans.id_train)) AS total_ticket
COUNT( CASE WHEN trans.id_user = 1
AND trans.id_train = 1 THEN 1
ELSE NULL END ) AS total_ticket
-- which may be simplified to
SUM(trans.id_user = 1 AND trans.id_train = 1) AS total_ticket
我想用 id_user 和 id_train 显示行序列 我可以在计数函数中嵌套 case 语句吗 sql?
我的 SQL 在这里,但它出错了
SELECT ticket.*
, COUNT( CASE trans.id_user WHEN 1 THEN 1
CASE trans.id_train WHEN 1 THEN 1
ELSE NULL END) AS total_ticket
, SUM(train.price) AS total_price
, user.*
FROM train JOIN trans ON trans.id_train = kereta.id_train
JOIN user ON trans.id_user = user.id_user
JOIN ticket ON ticket.train = train.id_train;
你可以这样做:
select COUNT( CASE trans.id_user WHEN 1
THEN 1
ELSE NULL
END) first_cnt
, COUNT( CASE trans.id_train WHEN 1
THEN 1
ELSE NULL
END) second_cnt
from trans;
但是,如果您想向 select 添加任何其他列,则需要按该列进行分组:
select trans.some_column
, COUNT( CASE trans.id_user WHEN 1
THEN 1
ELSE NULL
END) first_cnt
, COUNT( CASE trans.id_train WHEN 1
THEN 1
ELSE NULL
END) second_cnt
from trans
group by trans.some_column;
在您的情况下,这意味着您需要按票证中的所有列进行分组,因为您使用此:ticket.*
,用户中的所有列,因为您使用 user.*
另请注意,以上所有内容均可应用于您的 select 中的 SUM
。
COUNT( CASE trans.id_user WHEN 1 THEN 1 CASE trans.id_train WHEN 1 THEN 1 ELSE NULL END ) AS total_ticket
结构不明确。看起来您需要以下变体之一。
COUNT( CASE WHEN trans.id_user = 1 THEN 1
WHEN trans.id_train = 1 THEN 1
ELSE NULL END ) AS total_ticket
-- which may be simplified to
SUM(1 IN (trans.id_user, trans.id_train)) AS total_ticket
COUNT( CASE WHEN trans.id_user = 1
AND trans.id_train = 1 THEN 1
ELSE NULL END ) AS total_ticket
-- which may be simplified to
SUM(trans.id_user = 1 AND trans.id_train = 1) AS total_ticket