2016-10-02 127 views
2

我的問題很簡單,但我堅持了2周,無法退後一步,看到可能的解決方案。如何將sql查詢的結果轉換爲csv格式

我有一個SQL查詢看起來像一個結果:

USR Count DATE 
u1  9 160920 
U1  2 160918 
U1  5 160922 
U2  19 160924 
U3  2 160919 
U3  1 160921 
U4  12 160921 

而且我想這個結果轉換爲CSV格式的樣子,使用BASH由於在工作中的服務器上的限制:

;160918;160919;160920;160921;160922;160923;160924 
U1;  2;  0;  9;  0;  5;  0;  0 
U2;  0;  0;  0;  0;  0;  0; 19 
U3;  0;  2;  0;  1;  0;  0;  0 
U4;  0;  0;  0; 12;  0;  0;  0 

我卡住了,我成功地將行轉換爲csv格式,但是當我嘗試在一行中重新組合重複用戶時,我失敗了。

你有任何提示或想法?

+0

你自己執行sql查詢嗎?你可以使用OUTFILE(mysql)或等價物嗎? – user993553

+0

您可以使用SQL假脫機來獲得您的結果 –

+1

我剛纔說過:我沒有看到你是如何從輸入(你的查詢結果)到預期的輸出。手動進行此項操作時,您應用了哪些規則? – Sven

回答

2
SELECT Z.Col1 AS " ", 
     MAX(CASE WHEN Z.Col3 = 160918 THEN Z.Col2 ELSE 0 END) "160918", 
     MAX(CASE WHEN Z.Col3 = 160919 THEN Z.Col2 ELSE 0 END) "160919", 
     MAX(CASE WHEN Z.Col3 = 160920 THEN Z.Col2 ELSE 0 END) "160920", 
     MAX(CASE WHEN Z.Col3 = 160921 THEN Z.Col2 ELSE 0 END) "160921", 
     MAX(CASE WHEN Z.Col3 = 160922 THEN Z.Col2 ELSE 0 END) "160922", 
     MAX(CASE WHEN Z.Col3 = 160923 THEN Z.Col2 ELSE 0 END) "160923", 
     MAX(CASE WHEN Z.Col3 = 160924 THEN Z.Col2 ELSE 0 END) "160924" 
    FROM 
     (
     SELECT * 
      FROM 
     (SELECT 'u1' AS Col1, 9 AS Col2, 160920 AS Col3) UNION ALL 
     (SELECT 'u1' AS Col1, 2 AS Col2, 160918 AS Col3) UNION ALL 
     (SELECT 'u2' AS Col1, 19 AS Col2, 160924 AS Col3) UNION ALL 
     (SELECT 'u3' AS Col1, 2 AS Col2, 160919 AS Col3) UNION ALL 
     (SELECT 'u4' AS Col1, 1 AS Col2, 160921 AS Col3) UNION ALL 
     (SELECT 'u4' AS Col1, 12 AS Col2, 160921 AS Col3) 
     ) Z 
    GROUP BY Z.Col1 
    ORDER BY Z.Col1 
; 
+0

稍微調整一下,結果就是我想要的。 非常感謝Teja! –

+0

Ur歡迎..... – Teja