[英]sql case when where limit 1
我很困惑為什么會這樣?
select case when COUNT(1)> 0
then remain_salary_money
else 0
end AS remainBorrowMoney
from salary_pay_detail
where project_id = 483984364271566848
and team_id = 491297935619784704
and DATE(CONCAT(`year`,'-',`month`,'-01')) < '2020-11-01'
ORDER BY create_time desc
LIMIT 1
和另一個 sql
select remain_salary_money
from salary_pay_detail
where project_id = 483984364271566848
and team_id = 491297935619784704
and DATE(CONCAT(`year`,'-',`month`,'-01')) < '2020-11-01'
ORDER BY create_time desc
LIMIT 1
我在第一個sql結果中得到1948484,339220是第二個 sql 結果。
您可以對兩條記錄進行映像:
| month | remain_salary_money | year | create_time|
| ----- | -------------------- | ---- | ---------- |
| 09 | 1948484 | 2020 | 2021-01-07 19:45:20|
| 10 | 339220 | 2020 | 2021-01-08 19:45:25 |
我想知道發生了什么?
這是為了測試
CREATE TABLE `test` (
`id` int NOT NULL AUTO_INCREMENT,
`month` int DEFAULT NULL,
`year` int DEFAULT NULL,
`money` int DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
插入 sql
INSERT INTO `test`(`id`, `month`, `year`, `money`, `create_time`) VALUES (1, 9, 2020, 1111, '2021-01-07 19:45:20');
INSERT INTO `test`(`id`, `month`, `year`, `money`, `create_time`) VALUES (2, 10, 2020, 2222, '2021-01-08 19:45:25');
測試 sql
select money from test where DATE(CONCAT(`year`,'-',`month`,'-01')) < '2020-11-01'
ORDER BY create_time desc
LIMIT 1;
select case when COUNT(1)> 0
then money
else 0 end from test where DATE(CONCAT(`year`,'-',`month`,'-01')) < '2020-11-01'
ORDER BY create_time desc
LIMIT 1;
顯然,我想知道為什么當計數(1)> 0 時 select 情況...無法返回339220
沒有分組依據的聚合 function 超過了整個集合。 您對計數返回的查詢是不確定的..
加上您按日期和月份過濾但按創建時間排序(不一致)的事實,那么我無法弄清楚您要做什么。
你想達到什么目的?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.