2017-05-26 40 views
-3

例如數據分組順序depands在SQL

orderid productid 
1   1 
1   2 
1   3 
2   2 
2   3 
3   1 
4   3 
4   2 
5   1 
6   2 
7   2 
8   1 
8   2 

結果是

odcnt orderid productid 
    2 3   1 
    2 5   1 
    2 6   2 
    2 7   2 
    2 2   2 
    2 2   3 
    2 4   2 
    2 4   3 
    1 8   1 
    1 8   2 
    1 1   1 
    1 1   2 
    1 1   3 
+6

哪裏odcnt列從何而來? – jarlh

+0

訂單和產品匹配總數。 like product 1 have only two order in single odcnt is 2,and for like like order 2 and 4 have like same item and two order same for multiple ... ... – Lee

回答

0

這是你在找什麼

select count(*) as odcnt, orderid, productid from Table 
    group by orderid, productid 
+0

我不認爲這是正確的,如果你有'group通過orderid,productid' – TriV

+0

,因爲他想要這樣的結果...否則詳細說明問題 – Ravi

+0

當然,他應該更清楚。 – TriV

0

你需要多個產品的細節和它的數量。如果你使用的是任何編程語言,那麼你可以很容易地實現,但與SQL你需要多個命令。像

SELECT COUNT(`orderid`) as 'odcnt',`orderid`,`productid` FROM `order` WHERE `productid`=1; 
SELECT COUNT(`orderid`) as 'odcnt',`orderid`,`productid` FROM `order` WHERE `productid`=2; 
SELECT COUNT(`orderid`) as 'odcnt',`orderid`,`productid` FROM `order` WHERE `productid`=3; 

一些東西(嘗試在上面嵌套查詢命令,但我不知道..)