2014-07-17 123 views
1
CREATE TABLE Table1 
    (`id` int, `group_id` int, `data_id` int, `value` varchar(19)) 
; 

INSERT INTO Table1 
    (`id`, `group_id`, `data_id`, `value`) 
VALUES 
    (1, 20, 15, 'Supplier'), 
    (2, 20, 1, 'Rahul'), 
    (3, 20, 2, 'Sharma'), 
    (4, 20, 3, '05/08/90'), 
    (5, 20, 4, 'india'), 
    (6, 21, 15, 'Consumer'), 
    (7, 21, 1, 'Rajesh'), 
    (8, 21, 2, 'Sharma'), 
    (9, 21, 3, '05/08/88'), 
    (10, 21, 4, 'india') 
; 

創建表,現在我一張由供應商或消費者價值觀列數據排序是這樣的: 對於消費者:這可以在my-sql中完成嗎?

f-name l-name dob  location 
----------------------------------- 
Rajesh Sharma 05/08/88 india 
and so on .... 

對於供應商

f-name l-name dob  location 
----------------------------------- 
Rahul Sharma 05/08/90 india 
+0

它必須是不同的列? –

+0

否插件是由插件生成的,插入的值是否可以根據消費者和供應商對數據進行排序? – puneet

+0

看看這對你是否有好處:http://sqlfiddle.com/#!2/44e9e/13 –

回答

0

首先,您需要從您擁有的實體屬性值存儲中創建記錄。你可以用不同的方式做到這一點。下面是使用group by的方法:

select max(case when data_id = 1 then value end) as fname, 
     max(case when data_id = 2 then value end) as lname, 
     max(case when data_id = 3 then value end) as dob, 
     max(case when data_id = 4 then value end) as location 
from table1 
group by group_id 
having max(case when data_id = 15 then value end) = 'Consumer'; 

having子句則過濾,雖然也可以添加列指定記錄的類型。

0

您可以創建這樣的簡單功能:

CREATE FUNCTION GET_DATA(P_TYPE INT ,P_GROUP_ID INT) RETURNS VARCHAR(19) DETERMINISTIC 
BEGIN 
    DECLARE var varchar(19); 
    select value into var from Table1 WHERE group_id = P_GROUP_ID and data_id = P_TYPE; 
return var; 
END// 



-- you can use like this 
select GET_DATA(1,20) FIRST_NAME, 
GET_DATA(2,20) LAST_NAME, 
GET_DATA(3,20) DOB, 
GET_DATA(4,20) LOCATION; 


-- or you can use like this 

select 
GET_DATA(15,a.group_id) Type, 
GET_DATA(1,a.group_id) FirstName, 
GET_DATA(2,a.group_id) LastName, 
GET_DATA(3,a.group_id) Dob, 
GET_DATA(4,a.group_id) Location 
from 
(select distinct group_id from Table1) as a; 

撥弄例如http://sqlfiddle.com/#!8/e9647/7