我有桌子
ID State District StationCode Status
---------------------------------------------------------------
1 Gujarat Banaskantha 12345 0
2 Gujarat Banaskantha 12345 0
3 M.P. Bhopal 22315 1
4 Gujarat Banaskantha 12349 0
5 Gujarat Banaskantha 12345 1
Run Code Online (Sandbox Code Playgroud)
我需要结果
State District Active InActive
-----------------------------------------------
Gujarat Banaskantha 2 1
M.P. Bhopal 0 1
Run Code Online (Sandbox Code Playgroud)
在这里,Active 和Inactive字段的总和Status基于域0或1
这意味着State古吉拉特邦,three有时出现0,但two重复的行StationCode - 12345.这意味着它将被视为One.
我有如下查询
select distinct
state,
District,
SUM(
Case
when Status=0 then 1
else 0 end
) AS Active,
SUM(
Case
when Status=1 then 1
else 0
end
) AS InActive
from
Station_Master
group by state, District
Run Code Online (Sandbox Code Playgroud)
但我无法将重复StationCode行计为单个.
我怎样才能做到这一点 ?
您可以唯一地过滤子查询中的行。尝试,
SELECT DISTINCT state, district,
SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) Active,
SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) InActive
FROM (
SELECT DISTINCT state, district, StationCode, status
FROM Station_Master
) a
GROUP BY state, district
Run Code Online (Sandbox Code Playgroud)
我想这可能会解决你的问题。我不是 100% 确定语法,但如果您可以尝试一下并让我知道它是否不起作用,我可以尝试为您调整它。这个想法是使用 Group By 创建一个派生表,首先消除您不想要的重复项,然后外部查询与原始查询相同 - 只是在派生表上。
SELECT Distinct
X.State,
X.District,
SUM(Case when X.Status=0 then 1 else 0 end) AS Active,
SUM(Case when X.Status=1 then 1 else 0 end) AS InActive
FROM
(Select State, District, StationCode, Status
From Station_Master
Group By State,District, StationCode, Status) as X
GROUP BY X.State, X.District
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3910 次 |
| 最近记录: |