gpt4 book ai didi

sql-server - 聚合函数返回 null

转载 作者:行者123 更新时间:2023-12-03 09:56:52 24 4
gpt4 key购买 nike

我有这个示例数据

+------+------------+------------+
| CODE | START_DATE | END_DATE |
+------+------------+------------+
| 0001 | 2012-01-01 | 2012-01-31 |
+------+------------+------------+
| 0001 | 2012-02-01 | 2012-02-29 |
+------+------------+------------+
| 0001 | 2012-03-01 | NULL |
+------+------------+------------+
| 0002 | 2012-02-01 | 2012-02-29 |
+------+------------+------------+
| 0002 | 2012-03-01 | 2012-03-31 |
+------+------------+------------+
| 0002 | 2012-04-01 | NULL |
+------+------------+------------+
| 0003 | 2012-02-01 | 2012-02-29 |
+------+------------+------------+
| 0003 | 2012-03-01 | 2012-03-31 |
+------+------------+------------+

动态链接

CREATE TABLE SAMPLE
(
CODE VARCHAR(4),
START_DATE DATETIME,
END_DATE DATETIME
)

INSERT INTO SAMPLE (CODE, START_DATE, END_DATE) VALUES ('0001', {d '2012-01-01'}, {d '2012-01-31'})
INSERT INTO SAMPLE (CODE, START_DATE, END_DATE) VALUES ('0001', {d '2012-02-01'}, {d '2012-02-29'})
INSERT INTO SAMPLE (CODE, START_DATE, END_DATE) VALUES ('0001', {d '2012-03-01'}, NULL)

INSERT INTO SAMPLE (CODE, START_DATE, END_DATE) VALUES ('0002', {d '2012-02-01'}, {d '2012-02-29'})
INSERT INTO SAMPLE (CODE, START_DATE, END_DATE) VALUES ('0002', {d '2012-03-01'}, {d '2012-03-31'})
INSERT INTO SAMPLE (CODE, START_DATE, END_DATE) VALUES ('0002', {d '2012-04-01'}, NULL)

INSERT INTO SAMPLE (CODE, START_DATE, END_DATE) VALUES ('0003', {d '2012-02-01'}, {d '2012-02-29'})
INSERT INTO SAMPLE (CODE, START_DATE, END_DATE) VALUES ('0003', {d '2012-03-01'}, {d '2012-03-31'})

我应该得到这些数据

+------+------------+------------+
| CODE | START_DATE | END_DATE |
+------+------------+------------+
| 0001 | 2012-01-01 | NULL |
+------+------------+------------+
| 0002 | 2012-02-01 | NULL |
+------+------------+------------+
| 0003 | 2012-02-01 | 2012-03-31 |
+------+------------+------------+

目前在 SQL Server 2005 中,我使用这个查询

SELECT  CODE,
MIN(START_DATE) AS START_DATE,
CASE
WHEN MAX(ISNULL(END_DATE, {d '9999-12-31'})) = {d '9999-12-31'}
THEN NULL
ELSE
MAX(END_DATE)
END AS END_DATE
FROM SAMPLE
GROUP BY CODE

我在作弊 截至日期 9999-12-31 的 NULL 值

我正在为此寻找更好的解决方案

谢谢

最佳答案

您可以利用 NULLNOT NULL 列的 COUNT 不同这一事实。所以脚本可以像这样:

SELECT  CODE,
MIN(START_DATE) AS START_DATE,
CASE
WHEN COUNT(*) > COUNT(END_DATE)
THEN NULL
ELSE
MAX(END_DATE)
END AS END_DATE
FROM SAMPLE
GROUP BY CODE

关于sql-server - 聚合函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13638990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com