2014-12-04 67 views
-1

這是tbl_counter我如何從SQL表retrive數據

refId  refMid  dateTimeStmp    volCtr1  volCtr2  volCtr3  volCtr4 
----------- ----------- ----------------------- ----------- ----------- ----------- ----------- 
3   DEVICE1  2014-03-01 00:00:00.000 100   200   300   400 
4   DEVICE1  2014-03-02 00:00:00.000 100   200   300   400 
5   DEVICE1  2014-03-03 00:00:00.000 100   200   300   400 
6   DEVICE2  2014-03-02 00:00:00.000 100   200   300   400 
7   DEVICE2  2014-03-03 00:00:00.000 100   200   300   400 
8   DEVICE3  2014-03-03 00:00:00.000 100   200   300   400 
9   DEVICE3  2014-03-01 00:00:00.000 100   200   300   400 
10   DEVICE5  2014-03-01 00:00:00.000 100   200   300   400 
11   DEVICE5  2014-03-02 00:00:00.000 100   200   300   400 
12   DEVICE5  2014-03-03 00:00:00.000 100   200   300   400 
13   DEVICE5  2014-03-04 00:00:00.000 100   200   300   400 
14   DEVICE6  2014-03-04 00:00:00.000 100   200   300   400 
15   DEVICE7  2014-03-02 00:00:00.000 100   200   300   400 
16   DEVICE8  2014-03-01 00:00:00.000 100   200   300   400 
17   DEVICE8  2014-03-02 00:00:00.000 100   200   300   400 
18   DEVICE8  2014-03-03 00:00:00.000 100   200   300   400 
19   DEVICE8  2014-03-04 00:00:00.000 100   200   300   400 

我的數據表我需要的是數據是按以下格式

DATE  DEVICE1 DEVICE2 DEVICE3 DEVICE4 DEVICE5 DEVICE6 DEVICE7 DEVICE8 
01-03-2014 1000   1000   1000     1000 
02-03-2014 1000 1000     1000   1000 1000 
03-03-2014 1000 1000 1000   1000     1000 
04-03-2014         1000 1000   1000 

(在結果表裝置* N colomn包含volCtr1 + volCtr2 + volCtr3 + volCtr4) 這可以通過爲每個DEVICE創建臨時表並使用連接來完成,但是我需要一個更好的方法(如果有的話)。

回答

1

試試這個:

SELECT dateTimeStmp, DEVICE1, DEVICE2, DEVICE3, DEVICE4, DEVICE5, DEVICE6, DEVICE7, DEVICE8 
FROM (SELECT CONVERT(DATE, c.dateTimeStmp) AS dateTimeStmp, 
      ('DEVICE' + CONVERT(VARCHAR(100), c.refMid)) AS ColHeader, 
      (c.volCtr1 + c.volCtr2 + c.volCtr3) DEVICEDATA 
     FROM tbl_counter c 
    ) AS A 
PIVOT(SUM(DEVICEDATA) FOR ColHeader IN (DEVICE1, DEVICE2, DEVICE3, DEVICE4, DEVICE5, DEVICE6, DEVICE7, DEVICE8)) AS P 

OR

SELECT CONVERT(DATE, c.dateTimeStmp) AS Date, 
     SUM(CASE WHEN c.refMid = 1 THEN c.volCtr1 + c.volCtr2 + c.volCtr3 ELSE 0 END) AS DEVICE1, 
     SUM(CASE WHEN c.refMid = 2 THEN c.volCtr1 + c.volCtr2 + c.volCtr3 ELSE 0 END) AS DEVICE2, 
     SUM(CASE WHEN c.refMid = 3 THEN c.volCtr1 + c.volCtr2 + c.volCtr3 ELSE 0 END) AS DEVICE3, 
     SUM(CASE WHEN c.refMid = 4 THEN c.volCtr1 + c.volCtr2 + c.volCtr3 ELSE 0 END) AS DEVICE4, 
     SUM(CASE WHEN c.refMid = 5 THEN c.volCtr1 + c.volCtr2 + c.volCtr3 ELSE 0 END) AS DEVICE5, 
     SUM(CASE WHEN c.refMid = 6 THEN c.volCtr1 + c.volCtr2 + c.volCtr3 ELSE 0 END) AS DEVICE6, 
     SUM(CASE WHEN c.refMid = 7 THEN c.volCtr1 + c.volCtr2 + c.volCtr3 ELSE 0 END) AS DEVICE7, 
     SUM(CASE WHEN c.refMid = 8 THEN c.volCtr1 + c.volCtr2 + c.volCtr3 ELSE 0 END) AS DEVICE8 
FROM tbl_counter c 
GROUP BY CONVERT(DATE, c.dateTimeStmp); 
+0

感謝,幫助... – 2014-12-04 11:21:51