我正在尝试使用sql查询来订购数据,但是几天后我尝试了一切我没有想法如何做到这一点,所以,我做了这个查询
SELECT bm, SUM(CASE WHEN glasao = 'da' THEN 1 ELSE 0 END) + SUM(CASE WHEN glasao = 'ne' THEN 1 ELSE 0 END) AS [Ukupno u Bazi], SUM(CASE WHEN glasao = 'da' THEN 1 ELSE 0 END)
AS Glasali, SUM(CASE WHEN glasao = 'ne' THEN 1 ELSE 0 END) AS [Nisu Glasali]
FROM dbo.siguranglas
WHERE bm IN ('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36') GROUP BY bm ORDER BY bm DESC
我得到了这个输出:
9 1 0 1
8 9 0 9
4 1 0 1
29 3 2 1
28 1 0 1
26 3 2 1
17 1 1 0
13 2 1 1
问题是,如何命令第一个columnt这样:
4 1 0 1
8 9 0 9
9 1 0 1
13 2 1 1
17 1 1 0
26 3 2 1
28 1 0 1
29 3 2 1
如果我能......还有一个问题,有人可以帮助我再做一件事吗,我希望所有这一切能够再增加一个专栏 (Column3 *(column3 + column4))* 100 AS百分比
我尝试了很多东西并阅读了许多帖子但没有运气:P也许这不可能吗?
答案 0 :(得分:0)
它们存储为文本值,因此按照这样的方式排序;对于数字排序,他们需要是数字:
order by cast(bm as int) asc
答案 1 :(得分:0)
您必须在排序
之前投放 BM 列试试这个
SELECT bm, SUM(CASE WHEN glasao = 'da' THEN 1 ELSE 0 END) + SUM(CASE WHEN glasao = 'ne' THEN 1 ELSE 0 END) AS [Ukupno u Bazi], SUM(CASE WHEN glasao = 'da' THEN 1 ELSE 0 END)
AS Glasali, SUM(CASE WHEN glasao = 'ne' THEN 1 ELSE 0 END) AS [Nisu Glasali]
FROM dbo.siguranglas
WHERE bm IN ('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17'
'18','19','20','21','22','23','24','25','26','27','28','29','30','31','32',
'33','34','35','36')
GROUP BY bm
ORDER BY cast(bm as int)DESC
答案 2 :(得分:0)
根据给出的细节,我不认为Group by和order by中使用的列bm是整数列。首先,将其转换为整数列。
select *, (Glasali * (Glasali + Nisu Glasali)) * 100 as percent
from
(
SELECT bm, SUM(CASE WHEN glasao = 'da' THEN 1 ELSE 0 END) + SUM(CASE WHEN glasao = 'ne' THEN 1 ELSE 0 END) AS [Ukupno u Bazi], SUM(CASE WHEN glasao = 'da' THEN 1 ELSE 0 END)
AS Glasali, SUM(CASE WHEN glasao = 'ne' THEN 1 ELSE 0 END) AS [Nisu Glasali]
FROM dbo.siguranglas
WHERE bm IN ('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36') GROUP BY bm ORDER BY bm DESC
) a
order by cast(bm as integer)
顺便说一句,我不认为你的计算是计算百分比的正确方法。 CAST是一个oracle函数
答案 3 :(得分:0)
当前结果,“bm”列似乎是一个字符串,对吧?
如果是这样,你需要在场上进行施法......
答案 4 :(得分:0)
我认为这是SQL服务器。你的问题不是很清楚,但我想你的意思是:
WITH preSum ( bm, Glasali, [Nisu Glasali] )
AS (
SELECT bm, SUM(CASE WHEN glasao = 'da' THEN 1
ELSE 0
END),
SUM(CASE WHEN glasao = 'ne' THEN 1
ELSE 0
END)
FROM dbo.siguranglas
WHERE bm IN ( '1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'11', '12', '13', '14', '15', '16', '17', '18',
'19', '20', '21', '22', '23', '24', '25', '26',
'27', '28', '29', '30', '31', '32', '33', '34',
'35', '36' )
GROUP BY bm
)
SELECT bm, Glasali + [Nisu Glasali] AS [Ukupno u Bazi], Glasali,
[Nisu Glasali],
Glasali / ( Glasali + [Nisu Glasali] ) * 100 AS [percent]
FROM preSum
ORDER BY cast(bm as int) DESC;