我有类似的问题:distinct values as new columns & count
但不是只有3个值(在上面的情况下:驱动程序),我有大约100万,所以我不能在我的代码中列出所有这些。我怎么能在SQLite中做到这一点?
所以我想要像i = 1到length(DISTINCT(driver))那样重复下面的代码:
SELECT model
, COUNT(model) as drives
, SUM(distance) as distance
, SUM(CASE WHEN driver=DISTINCT(driver)[i] THEN 1 ELSE 0 END) AS DISTINCT(driver)[i]
FROM new_table
GROUP BY model;
答案 0 :(得分:0)
SQLite没有动态SQL机制。您必须从数据库中读取所有可能的驱动程序列表,并为程序中的每个值构建一个单独的SUM(CASE ...)列的查询。
但是大量的列效率很低,当它大于2000时,它无论如何都不会起作用。 最好单独返回每个矩阵条目:
@MethodDescription(value = "Return the Server Sent Event")
@GET
@Consumes(SseFeature.SERVER_SENT_EVENTS)
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput getServerSentEvents() {
id = id + 1;
idn = sensorA + " " + id;
final EventOutput eventOutput = new EventOutput();
Client client = ClientBuilder.newBuilder().register(SseFeature.class).build();
WebTarget target = client.target("http://" + LocalNetworkIP + "/" + sensorA);
final EventInput eventInput = target.request().get(EventInput.class);
new Thread(new Runnable() {
@Override
public synchronized void run() {
try {
while (!eventInput.isClosed()) {
// Thread.sleep(500);
InboundEvent inboundEvent = eventInput.read();
if (inboundEvent == null) {
break; // connection has been closed
}
try {
// handleevent
// inboundEvent.readData(String.class);
System.out.println(inboundEvent.readData(String.class));
OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
eventBuilder.name(inboundEvent.getName());
eventBuilder.data(inboundEvent.readData(String.class));
OutboundEvent event = eventBuilder.build();
eventOutput.write(event);
} catch (IOException e) {
try { //extra
eventOutput.close(); //extra
eventInput.close(); //extra
} catch (IOException ioClose) { //extra
throw new RuntimeException("Error when closing the event output internal.", ioClose); //extra
} //extra
throw new RuntimeException("Error when writing or reading the event.", e);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (!eventOutput.isClosed()) { //extra
eventOutput.close(); //extra
} //extra
if (!eventInput.isClosed()) { //extra
eventInput.close();
} //extra
} catch (IOException ioClose) {
throw new RuntimeException("Error when closing the event output.", ioClose);
}
}
}
}).start();
return eventOutput;
}
}