按多个联接中的查询错误分组

时间:2016-06-07 07:12:23

标签: sql sql-server join

我需要在单个查询中获取每个选择项及其计数。这是我的查询并期望输出为单个数组。

select ordetable.order_id, count(ordetable.order_id), order_table.name,
       count(order_table.na me), orderitem_table.itemname,
       count(orderitem_table.itemname)
from order_table
left join orderitem_table
    on order_table.order_id = orderitem_table.order_id
group by ordetable.order_id

我收到此错误:

  

[Microsoft] [SQL Server的ODBC驱动程序11] [SQL Server]列   ' orderitem_table.itemname'在选择列表中无效,因为它是   不包含在聚合函数或GROUP BY子句中。

3 个答案:

答案 0 :(得分:2)

问题从错误消息中可以看出,不是吗?

修改您的查询,如下所示。

public class Combine {

public static void main(String[] args) {

    List<Integer> list1 = new ArrayList<Integer>();
    for (int i = 0; i < 140; i++) {
        list1.add(i);
    }
    List<Integer> list2 = new ArrayList<Integer>();
    for (int i = 200; i < 350; i++) {
        list2.add(i);
    }

    List<Integer> list3 = new ArrayList<Integer>();
    for (int i = 300; i < 350; i++) {
        list3.add(i);
    }

    List<List> list = new ArrayList<List>();
    list.add(list1);
    list.add(list2);
    list.add(list3);
    long startTime = System.currentTimeMillis();
    System.out.println(doCombine(list).size());
    long stopTime = System.currentTimeMillis();
    System.out.println(stopTime - startTime);

}

public static List<String> doCombine(List<List> list) {

    List<String> tempList = new ArrayList<String>();
    List<String> resultList = new ArrayList<String>();

    for (int i = 0; i < list.get(0).size(); i++) {
        resultList.add(String.valueOf(list.get(0).get(i)));
    }

    StringBuilder sb;
    for (int i = 1; i < list.size(); i++) {
        for (String tempItem : resultList) {
(1)         sb = new StringBuilder(tempItem);
            for (int j = 0; j < list.get(i).size(); j++) {
 (2)                   sb = new StringBuilder(tempItem);                     
tempList.add(String.valueOf(sb.append(":").append(list.get(i).get(j))));
                }
            }
            resultList = tempList;
            tempList = new ArrayList<String>();
        }
        return resultList;
    }
    }

答案 1 :(得分:2)

如果您不想将order_table.name和orderitem_table.itemname分组,那么您可以使用'min'条件。

select ordetable.order_id, count(ordetable.order_id), min(order_table.name),
       count(order_table.name), min(orderitem_table.itemname),
       count(orderitem_table.itemname)
from order_table
left join orderitem_table
    on order_table.order_id = orderitem_table.order_id
group by ordetable.order_id

答案 2 :(得分:1)

您的措辞和查询不同步。每个项目及其计数(在所有订单上)将是

select orderitem_table.itemname, orderitem_table.itemnumber, count(*)
from order_table
join orderitem_table
    on order_table.order_id = orderitem_table.order_id
group by orderitem_table.itemname, orderitem_table.itemnumber