gpt4 book ai didi

sql - 如何在同一张表中以不同条件检索同一列两次?

转载 作者:太空狗 更新时间:2023-10-30 01:48:23 24 4
gpt4 key购买 nike

这是我的 table :

Anganbadi_ID               Food     Month
-------------------------------------------
1165 हाँ 1
1165 हाँ 2
1165 हाँ 4
1168 हाँ 4
2032 नहीं 4
2218 नहीं 4
2219 हाँ 4
2358 नहीं 4
2546 हाँ 10

有 4 列 Anganbadi_ID, Food, Month, Year 我想根据两个不同的月份值比较 Food 列两次。

例如如果我为第一个食物 (Food-1) 列选择 Month=4,为第二个食物 (Food-2) 列选择 Month=10,那么它应该如下所示::

Anganbadi_ID            Food-1     Food-2    
------------------------------------------
1165 हाँ NULL
1168 हाँ NULL
2032 नहीं NULL
2218 नहीं NULL
2219 हाँ NULL
2358 नहीं NULL
2546 NULL हाँ

当我尝试这段代码时

SELECT     
Anganbadi_ID, Food,
(SELECT Food
FROM Anganbadi AS Anganbadi_2
WHERE (Anganbadi_1.Anganbadi_ID = Anganbadi_ID)
AND (Anganbadi_1.Month = 10)
) AS 'Food(2)'
FROM Anganbadi AS Anganbadi_1
WHERE (Month = 4)

它显示以下结果::

Anganbadi_ID              Food-1     Food-2    
--------------------------------------------
1165 हाँ NULL
1168 हाँ NULL
2032 नहीं NULL
2218 नहीं NULL
2219 हाँ NULL
2358 नहीं NULL

请尽快帮助我....

最佳答案

SELECT DISTINCT Anganbadi_ID,

(SELECT Food
FROM Anganbadi
WHERE (Anganbadi_ID = A.Anganbadi_ID)
AND (Month = 4)) AS Food1,

(SELECT Food
FROM Anganbadi
WHERE (Anganbadi_ID = A.Anganbadi_ID)
AND (Month = 10)) AS Food2

FROM Anganbadi AS A
WHERE A.Month = 10 OR A.Month = 4

SQL Fiddle

关于sql - 如何在同一张表中以不同条件检索同一列两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16423883/

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