在mysql中按行项目分组

时间:2013-03-12 19:18:11

标签: mysql

我需要每行的一列结果不同。

这是数据的显示方式:

Ticketnumber  Legnumber  Commission
100           1          50
100           2          50

这就是我需要它出现的方式:

Ticketnumber  Legnumber  Commission
100           1          100
100           2          0

因此,当legnumber = 1时,我需要按照ticketnumber分组的佣金,但是当legnumber> 1佣金应为零。我试着写一个案例陈述无济于事。有关如何完成此任务的任何建议?

4 个答案:

答案 0 :(得分:0)

使用GROUP BY和内部表格

SELECT TicketNumber, LegNumber, 
CASE WHEN LegNumber = 1 THEN 
(SELECT SUM(Commission)  
FROM MyTable WHERE TicketNumber = MT.TicketNumber 
GROUP BY TicketNumber) ELSE 0 END AS Commission 
FROM MyTable MT

小提琴 - http://www.sqlfiddle.com/#!2/00a95/6

答案 1 :(得分:0)

您可以使用Group By属性

SELECT Table1.TicketNumber, LegNumber
, CASE WHEN LegNumber = 1 THEN SUM(Table2.Commission) ELSE 0 END AS Commission 
FROM Table1 JOIN (SELECT TicketNumber, sum(commission) as commission
                  FROM table1
                  GROUP BY TicketNumber) table2
ON TABLE1.TICKETNUMBER = table2.ticketnumber
GROUP BY Table1.TicketNumber, LegNumber
ORDER BY Table1.TicketNumber, LegNumber

SQL Fiddle

答案 2 :(得分:0)

试试这个

 SELECT TicketNumber, LegNumber, 
 CASE WHEN LegNumber = 1 
      THEN (select SUM(Commission) from Table1  group by ticketnumber   ) 
      ELSE 0 END AS Commission 
 FROM Table1 GROUP BY TicketNumber, LegNumber

DEMO HERE

答案 3 :(得分:0)

我会使用这个解决方案:

SELECT
  t1.Ticketnumber,
  t1.Legnumber,
  CASE WHEN Legnumber=1 THEN t2.sum_commission ELSE 0 END Commission
FROM
  Table1 t1 INNER JOIN (
    SELECT Ticketnumber, SUM(Commission) sum_commission
    FROM Table1
    GROUP BY Ticketnumber
  ) t2
  USING (Ticketnumber)
ORDER BY 
  t1.Ticketnumber,
  t1.Legnumber

请参阅小提琴here