SQL选择使用distinct和Cast

时间:2012-10-09 13:27:30

标签: sql select casting distinct

  

可能重复:
  SQL Select DISTINCT using CAST

让我再试一次......我不是一个sql的家伙所以请耐心等待我解释这个...我有一个名为t_recordkeepingleg的表,有三列数据。 Column1名为LEGTRIPNUMBER,恰好是以字母Q后跟4个数字开头的字符串。我需要剥离Q并将剩余的4个字符(数字)转换为整数。到目前为止每个人都和我在一起该表的Column2名为LEGDATE。 Column3名为LEGGROUP

这是输入方案

LEGTRIPNUMBER    LEGDATE      LEGGROUP
Q1001            08/12/12       0001
Q1001            09/15/12       0002
Q1002            09/01/12       0001
Q1002            09/08/12       0003
Q1002            09/09/12       0002

正如您所看到的,输入表包含多次出现LEGTRIPNUMBER的行。我只希望第一次出现。

这是我当前的select语句 - 它可以工作但返回所有行。

SELECT *, 
   CAST(
       substring("t_RecordkeepingLeg"."LEGTRIPNUMBER",2,4) as INT
   ) as Num_Trip_Num
   FROM   "1669"."dbo"."t_RecordkeepingLeg" "t_RecordkeepingLeg" 
   Where left "t_RecordkeepingLeg"."LEGTRIPNUMBER",1) = 'Q'

我想修改它,以便它只选择一个Qnnnn的出现。选中该行后,我希望LEGDATELEGGROUP可供我使用。我该怎么做呢?

谢谢,

3 个答案:

答案 0 :(得分:0)

可以像下面一样简单吗?我刚刚添加了leggroup的条件为0001

SELECT *,  
   CAST(substring("t_RecordkeepingLeg"."LEGTRIPNUMBER",2,4) as INT) as Num_Trip_Num 
 FROM   "1669"."dbo"."t_RecordkeepingLeg" "t_RecordkeepingLeg"  
 Where left ("t_RecordkeepingLeg"."LEGTRIPNUMBER",1) = 'Q'
    and "t_RecordkeepingLeg"."LEGGROUP"='0001'

答案 1 :(得分:0)

如果您的表格中有唯一的主键,则可以执行以下操作;

SELECT CAST(
   substring("t_RecordkeepingLeg"."LEGTRIPNUMBER",2,4) as INT
) as Num_Trip_Num
FROM   "1669"."dbo"."t_RecordkeepingLeg" "t_RecordkeepingLeg" 
Where "t_RecordkeepingLeg"."ID" In(
   Select Min("t_RecordkeepingLeg"."ID")
   From "1669"."dbo"."t_RecordkeepingLeg" "t_RecordkeepingLeg" 
   Where left ("t_RecordkeepingLeg"."LEGTRIPNUMBER",1) = 'Q'
   Group By "t_RecordkeepingLeg"."LEGTRIPNUMBER"
)

答案 2 :(得分:0)

LEGDATE&的哪些LEGGROUP你想要的是LEGTRIPNUMBER吗?存在多种不同的可能性,“第一次出现”的概念仅对明确的顺序有效。

获取LEGDATE最早的值,例如

select Num_Trip_Num, LEGDATE, LEGGROUP from (
    select
       cast(substring(t_RecordkeepingLeg.LEGTRIPNUMBER, 2, 4) as INT) as Num_Trip_Num,
       row_number() over (partition by substring(t_RecordkeepingLeg.LEGTRIPNUMBER, 2, 4) order by t_RecordkeepingLeg.LEGDATE asc) as row,
       t_RecordkeepingLeg.LEGDATE,
       t_RecordkeepingLeg.LEGGROUP
    from t_RecordkeepingLeg
       where left (t_RecordkeepingLeg.LEGTRIPNUMBER, 1) = 'Q'
) T
    where row = 1