0

我正在开发一个使用 Java 和 SQL 以及 Oracle 数据库的数据库项目。我是使用数据库的新手,也是 SQL 的新手。我的问题是:我如何才能获得客户数量并将他们的每个购买历史记录在数据透视表上?例如,下表中,我有 Lee 总共 3 次,购买了 Item A、Item B 和 Item C。Ann 也有 3 次,并购买了 Item D、Item E 和 Item F。我想要把他们的名字、出现的次数和他们购买的东西放在单独的数据透视表上。

Row       Customer      Purchase_History
 1          Lee              Item A
 2          Lee              Item B
 3          Lee              Item C
 4          Ann              Item D
 5          Ann              Item E
 6          Ann              Item F

我已经编写了一些代码试图做到这一点,但是当我编译和运行时,它不会给我想要的结果。这是我的代码:

           String TableCount = "SELECT J.Row, J.Customer, J.Purchase_History, C.cnt" +
                " FROM Table J INNER JOIN(SELECT Customer, count(Customer) as cnt" +
                "FROM Table GROUP BY Customer") C ON J.Customer = C.Customer;
         ResultSet rs = st.executeQuery(TableCount);


         while(rs.next()){

             st.executeUpdate("CREATE TABLE IF NOT EXISTS CUSTOMER_COUNT" +
                        "(TableCount  , Purchase_History )");
            String InsertIntoTable = String.format("INSERT INTO CUSTOMER_COUNT" +
                        "("TableCount","Purchase_History")" +
                        " VALUES ('%s','%s)");
         }

我在这里做错了什么?任何帮助将不胜感激!

4

1 回答 1

0

您的查询逻辑很好。您应该在运行之前打印出查询。问题将是这两行(至少):

            " FROM Table J INNER JOIN(SELECT Customer, count(Customer) as cnt" +
            "FROM Table GROUP BY Customer") C ON J.Customer = C.Customer;

我假设你的意思是:

            " FROM Table J INNER JOIN(SELECT Customer, count(Customer) as cnt" +
            "FROM Table GROUP BY Customer) C ON J.Customer = C.Customer";

无论如何,当您打印出来时,您将拥有表达式cntFROM table. 你需要一个空间:

            " FROM Table J INNER JOIN(SELECT Customer, count(Customer) as cnt" +
            " FROM Table GROUP BY Customer) C ON J.Customer = C.Customer";

但是,编写查询的更简单方法是使用分析函数:

select J.Row, J.Customer, J.Purchase_History,
       count(*) over (partition by customer) as cnt
from table j
于 2013-07-08T14:45:16.560 回答