请帮忙, 这是我的表
date column1 column2 trx
2015-07-01 **side1 Internet** 777903315
2015-07-01 **side1 Internet** 41426210
2015-07-01 side1 Unlimited 2263500
2015-07-01 side1 Business 427000
2015-07-01 side1 Extreme 3540900
2015-07-01 side1 Lifestyle 59360000
2015-07-01 side1 Socialita 240850500
2015-07-01 **side2 Unlimited** 6160
2015-07-01 **side2 Unlimited** 113502000
我想选择我的表格,结果如下:
date column1 column2 trx type
2015-07-01 **side1 Internet** 777903315 pre
2015-07-01 **side1 Internet** 41426210 post
2015-07-01 side1 Unlimited 2263500 pre
2015-07-01 side1 Business 427000 pre
2015-07-01 side1 Extreme 3540900 pre
2015-07-01 side1 Lifestyle 59360000 pre
2015-07-01 side1 Socialita 240850500 pre
2015-07-01 **side2 Unlimited** 6160 post
2015-07-01 **side2 Unlimited** 113502000 pre
在column1和column2中具有相同值的行,在最小trx添加字段后面的行作为类型'post'和最大化'pre'
答案 0 :(得分:1)
您可以使用以下查询:
SELECT m.*,
CASE trx
WHEN mintrx THEN 'post'
WHEN maxtrx THEN 'pre'
ELSE 'pre'
END AS type
FROM mytable AS m
LEFT JOIN (
SELECT column1, column2, MIN(trx) AS mintrx, MAX(trx) AS maxtrx
FROM mytable
GROUP BY column1, column2
HAVING MIN(trx) <> MAX(trx) ) AS t
ON m.column1 = t.column1 AND m.column2 = t.column2
此查询执行LEFT JOIN
,其派生表仅包含重复的column1
,column2
行。最小/最大trx
匹配分别生成post
/ pre
值,而pre
是非匹配表行的默认值。
答案 1 :(得分:0)
SELECT t.date, t.c1, t.c2, t.trx
, CASE WHEN t.trx = m.trx THEN 'pre' ELSE 'post' END AS `type`
FROM so_q31531850 t
LEFT OUTER JOIN ( SELECT DATE, c1, c2, MAX(trx) AS trx FROM so_q31531850 GROUP BY 1,2,3) m
ON m.trx = t.trx AND m.c1 = t.c1 AND m.c2 = t.c2 AND m.date = t.date
请注意,如果交易号相同,我建议的查询会将其视为post
条目类型。
答案 2 :(得分:0)
下面的查询(SQL)以上面给出的所需格式给出结果:
SELECT Date,column1,column2,trx
,CASE RANK() OVER(PARTITION BY Date,col1,col2 ORDER BY trx DESC)
WHEN 1 THEN 'pre'
ELSE 'post'
END as type
FROM [TableName]
答案 3 :(得分:0)
也许这段代码可以做得更好一点,我自己也不是一个sql人,但是小提琴很有趣。
这是一个示例表:
CREATE TABLE EXAMPLE (
id INT,
c1 NVARCHAR(100),
c2 NVARCHAR(100)
);
INSERT INTO EXAMPLE (ID,c1,c2)
VALUES (1, '**side1', 'Internet**');
INSERT INTO EXAMPLE (ID,c1,c2)
VALUES (2, '**side2', 'Unlimited**');
INSERT INTO EXAMPLE (ID,c1,c2)
VALUES (3, 'side1', 'Unlimited');
INSERT INTO EXAMPLE (ID,c1,c2)
VALUES (4, 'side1', 'Lifestyle');
INSERT INTO EXAMPLE (ID,c1,c2)
VALUES (5, 'side1', 'Buisness');
INSERT INTO EXAMPLE (ID,c1,c2)
VALUES (6, '**side2', 'Unlimited**');
INSERT INTO EXAMPLE (ID,c1,c2)
VALUES (7, '**side1', 'Internet**');
查询:
select * from Example
order by
case
when c1 like '**%' then substring(c1,3,Len(c1)) else c1
end,c1 ,c2 desc;