在mysql中选择一个表两次,以获取行数据到列数据

时间:2013-10-15 11:10:43

标签: mysql select

我有一个包含以下列的表

Date        recd_amt    paid_amnt  counter

2013-01-01  899.00      120.00      1  
2013-01-02  6988.00     255.00      1  
2013-01-03  94.89       259.00      1  
2013-01-01  589.50      255.00      2  
2013-01-02  745.00      569.00      2  
2013-01-03  298.00      985.00      2  
2013-01-04  449.00      312.00      2  
2013-01-04  271.00      255.00      1  

我想以这种方式付出

Date              Counter-1                      Counter 2
            Recd Amt     Paid amnt          Recd amnt  Paid amnt

2013-01-01   899.00    120.00                 589.50     255.00

我试过这个sql但没有工作。请说明我的错误。

select date, 
    case when unit='1' then act_h3 end as u1acth3, 
    case when unit='1' then act_gb end  as u1actgb  
from systemactivity A 
   left join (select case when unit='2' then act_h3 end as u2acth3, 
                     case when unit='2' then act_gb end  as u2actgb 
              from systemactivity)b 
       on A.date = B.date 

2 个答案:

答案 0 :(得分:1)

我不打算弄清楚你的列名,因为它们看起来很残忍(对不起),但这里是你想要的通用SQL结构

SELECT t1.date, t1.recd_amt, t1.paid_amt, t2.recd_amt, t2.paid_amt
FROM systemactivity t1
LEFT JOIN systemactivity t2
    ON t1.date = t2.date
    AND t2.counter = 2
WHERE t1.counter = 1

答案 1 :(得分:1)

你的意思是这样的:

select sa1.date, sa1.recd_amnt, sa1.paid_amnt, sa2.recd_amnt, sa2.paid_amnt
from systemactivity sa1
join systemactivity sa2 on sa2.date = sa1.date
where sa1.counter = 1 and sa2.counter = 2;