select
'N' as Content,
(select COUNT(*) from TB1 ) as [Sample Analyzed ],
(select COUNT(*) from TB1 where convert(float,D) between 0.0005 and 0.75) as [Very Low],
(select COUNT(*) from TB1 where convert(float,D) between 0.76 and 1.25 ) as [Low]
union
select 'P' as Content,
(select COUNT(*) from TB1 ) as [Sample Analyzed ],
(select COUNT(*) from TB1 where convert(float,C) between 0.0005 and 0.75) as [Very Low],
(select COUNT(*) from TB1 where convert(float,C) between 0.76 and 1.25 ) as [Low]
union
select 'K' as Content,
(select COUNT(*) from TB1 ) as [Sample Analyzed ],
(select COUNT(*) from TB1 where convert(float,B) between 0.0005 and 0.75) as [Very Low],
(select COUNT(*) from TB1 where convert(float,B) between 0.76 and 1.25 ) as [Low]
union
select 'OC' as Content,
(select COUNT(*) from TB1 ) as [Sample Analyzed ],
(select COUNT(*) from TB1 where convert(float,A) between 0.0005 and 0.75) as [Very Low],
(select COUNT(*) from TB1 where convert(float,A) between 0.76 and 1.25 ) as [Low]
ORDER BY
(
CASE
WHEN Content = 'N' THEN 0
WHEN Content = 'P' THEN 1
WHEN Content = 'K' THEN 2
WHEN Content = 'OC' THEN 3
ELSE 4
END
)
答案 0 :(得分:1)
...列名'内容'无效....
那是因为您无法在ORDER BY
如果语句,ORDER BY项必须出现在选择列表中 包含UNION,INTERSECT或EXCEPT运算符
那是因为列别名不是select的一部分,与上面相同。它不是一个实际的列(还)
以下是将其包装在CTE
。
with cte as(
select
'N' as Content,
(select COUNT(*) from TB1 ) as [Sample Analyzed ],
(select COUNT(*) from TB1 where convert(float,D) between 0.0005 and 0.75) as [Very Low],
(select COUNT(*) from TB1 where convert(float,D) between 0.76 and 1.25 ) as [Low]
union
select 'P' as Content,
(select COUNT(*) from TB1 ) as [Sample Analyzed ],
(select COUNT(*) from TB1 where convert(float,C) between 0.0005 and 0.75) as [Very Low],
(select COUNT(*) from TB1 where convert(float,C) between 0.76 and 1.25 ) as [Low]
union
select 'K' as Content,
(select COUNT(*) from TB1 ) as [Sample Analyzed ],
(select COUNT(*) from TB1 where convert(float,B) between 0.0005 and 0.75) as [Very Low],
(select COUNT(*) from TB1 where convert(float,B) between 0.76 and 1.25 ) as [Low]
union
select 'OC' as Content,
(select COUNT(*) from TB1 ) as [Sample Analyzed ],
(select COUNT(*) from TB1 where convert(float,A) between 0.0005 and 0.75) as [Very Low],
(select COUNT(*) from TB1 where convert(float,A) between 0.76 and 1.25 ) as [Low]
)
select * from cte
ORDER BY
(
CASE
WHEN Content = 'N' THEN 0
WHEN Content = 'P' THEN 1
WHEN Content = 'K' THEN 2
WHEN Content = 'OC' THEN 3
ELSE 4
END
)