0

可能重复:
SQL 使用 CAST 选择 DISTINCT

让我再试一次......我不是一个 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 *, 
   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可供我使用。我该怎么做呢?

谢谢,

4

3 回答 3

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'
于 2012-10-09T13:33:03.843 回答
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"
)
于 2012-10-09T13:36:38.987 回答
0

对于 distinct ,您想要LEGDATE&的哪些值?有多种不明确的可能性,“第一次出现”的概念只有在明确的顺序下才有效。LEGGROUPLEGTRIPNUMBER

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
于 2012-10-09T13:47:09.723 回答