分组在一起的不同选择语句的SQL问题

时间:2014-06-23 20:40:51

标签: sql sql-server

我在解决这个问题时遇到了困难。我有一张桌子 称为KpiSetupOee,列名为OeeID,FkEquipmentType,Nominal,Low。

enter image description here

我有一个select语句,它给出了Nkinal值,其中FkEquipmentType等于'WM'

Select * from KpiSetupOee where FkEquipmentType =’WM’

然后我想组合另一个select语句来检索除FkEquipmentType<>之外的最低标称值。 “WM”

Select top 1 * from KpiSetupOee where FlEquipmentType <>’WM’ Order by Nominal asc

当我单独运行时,我得到了两个select语句的正确答案。当我在中间做一个联合时,我得到第一个陈述的正确答案,但第二个答案是错误的答案。第二个选择不给我最低的标称值。有谁知道我做错了什么?是否有更简单的查询可以获得这些值?首先选择哪个语句无关紧要。我只需要设备类型为“WM”的值(标称值,低值),以及设备类型不等于WM时其余值的最低标称值。有什么建议?谢谢你的帮助

Select * from KpiSetupOee where FkEquipmentType =’WM’
Union all
Select top 1 * from KpiSetupOee where FlEquipmentType <>’WM’ Order by Nominal asc

2 个答案:

答案 0 :(得分:3)

而是通过将select包裹在()

中来尝试您的查询

对于MySQL,语法如下。看到这个小提琴http://sqlfiddle.com/#!2/18ab2/2

(Select * from tab1 where FkEquipmentType = 'WM')
Union all
(Select * from tab1 where FkEquipmentType <> 'WM' 
 Order by Nominal asc limit 1);

对于SQL Server,语法如下所示。请参阅此处了解演示http://sqlfiddle.com/#!3/18ab2/11

Select oeeid, FkEquipmentType,nominal,low
from tab1 where FkEquipmentType ='WM'
Union all
select oeeid, FkEquipmentType,nominal,low 
from
  (
  Select *,ROW_NUMBER() OVER (ORDER BY nominal) as rn from tab1 
  where FkEquipmentType <> 'WM' 
  ) X where rn = 1;

答案 1 :(得分:2)

您可以使用查询执行此操作:

SELECT TOP 2 * FROM (Select 1 as 'RowNum', OeeID, FkEquipmentType, Nominal, Low from #KpiSetupOee where FkEquipmentType ='WM'
Union
Select 2, OeeID, FkEquipmentType, Nominal, Low from #KpiSetupOee where FkEquipmentType <> 'WM') A Order by 'RowNum', Nominal asc 

这种方法的好处是它始终确保行FkEquipmentType为&#39; WM&#39;始终是返回查询中的第一行。

在此处查看 - &gt; http://sqlfiddle.com/#!3/e39f6/1http://sqlfiddle.com/#!3/656a2/1

希望这有帮助!!!