db2特定查询不同行的计数

时间:2014-11-19 14:26:36

标签: sql db2 ibm-midrange

我正在使用DB2。我有这个问题:

SELECT DISTINCT 
ORDER_NUMBER,
trdm as TRADEMARK,
cmdnsm as CUSTOMER_NAME
FROM DB1.ORDFA
JOIN DB2.CCADF ON SFORD# = WDRSO
JOIN DB2.DADA06 ON WD3ADF = WD3FLA
JOIN DB1.CMP1 ON C1LK2 = SF2LK
WHERE YEAR = '14' AND PART = '5484'
ORDER BY CUSTOMER_NAME, TRADEMARK

我从上面的查询中得到了这个结果集

order_number    trademark      customer_name
  2220824.        AIR          EPR PRODUCTS INC
  2254614.       AVALON        EPR PRODUCTS INC
  2214146.       AVALON        EPR PRODUCTS INC
  2338002.       AVALON        EPR PRODUCTS INC
  2102733.       BOSS          EPR PRODUCTS INC
  2286148.        CDC          EPR PRODUCTS INC
  2116148.        CDC          EPR PRODUCTS INC
  2032105.        HC           SUMMLC
  2014046.        HC           SUMMLC
  2232312.       SDEXO         SUMMLC
  2267369.       SDEXO         SUMMLC
  2085280.       SDEXO         SUMMLC
  2170433.       SDEXO         SUMMLC
  2179283.       SDEXO         SUMMLC
  2378745.       SDEXO         SUMMLC

我需要的是一个DB2查询,它会给我这个结果集:

 NUM_ORDERS      TRADEMARK      CUSTOMER_NAME
     6            SDEXO          SUMMLC
     3            AVALON         EPR PRODUCTS INC
     2            CDC            EPR PRODUCTS INC
     2            HC             SUMMLC
     1            BOSS           EPR PRODUCTS INC
     1            AIR            EPR PRODUCTS INC

2 个答案:

答案 0 :(得分:4)

如果DB2支持ansi标准sql,我相信您只需要添加countgroup by

SELECT 
    COUNT(DISTINCT ORDER_NUMBER) AS NUM_ORDERS,
    trdm as TRADEMARK,
    cmdnsm as CUSTOMER_NAME
FROM DB1.ORDFA
JOIN DB2.CCADF ON SFORD# = WDRSO
JOIN DB2.DADA06 ON WD3ADF = WD3FLA
JOIN DB1.CMP1 ON C1LK2 = SF2LK
WHERE YEAR = '14' AND PART = '5484'
GROUP BY trdm, cmdnsm
ORDER BY NUM_ORDERS DESC, CUSTOMER_NAME, TRADEMARK

答案 1 :(得分:2)

尝试这样的事情:

SELECT COUNT(DISTINCT ORDER_NUMBER) AS ORDER_NUMBER,
TRADEMARK,
CUSTOMER_NAME
FROM DB1.ORDFA
JOIN DB2.CCADF ON SFORD# = WDRSO
JOIN DB2.DADA06 ON WD3ADF = WD3FLA
JOIN DB1.CMP1 ON C1LK2 = SF2LK
WHERE YEAR = '14' AND PART = '5484'
GROUP BY CUSTOMER_NAME, TRADEMARK
ORDER BY ORDER_NUMBER DESC