SQL连接在一列上的投影计数

时间:2018-07-23 22:58:23

标签: sql sql-server

我想把头放在围绕2个表的SQL查询上。我还没找到路。

客户:

| id| firstname | lastname | email   | customertype | state  |
| 1 | joe       | doe      | joe@doe | walk in      | active |
| 2 | foo       | bar      | foo@bar | contractor   | active |

顺序:

| id| customerid | itemname  | itemtype | cost   | date
| 1 | 2          | pull      | t1       | 2.99   | 2018-07-24
| 2 | 1          | push      | t3       | 0.99   | 2018-06-01
| 3 | 2          | push      | t3       | 0.99   | 2018-05-13

想法是计算每种商品类型(例如contractar的某些类型的用户订购了多少商品)。

库存的物品只有3种:t1,t2,t3。所以我需要将类型的计数设计如下:

| customerid | firstname | lastname | t1 | t2 | t3 |
| 2          | foo       | bar      | 1  | 0  | 1  |

select customerid,
       firstname,
       lastname,
       t1 = (select count(t1) from order where item type = t1),
       t2 = (select count(t2) from order where item type = t2),
       t3 = (select count(t3) from order where item type = t3),
       from order join customer on order.customerid = customer.id
       where customer.customertype = 'contractor' and date > dateadd(day,-7,getdate())

2 个答案:

答案 0 :(得分:1)

查询中出现问题的根本原因是,您没有在Select子查询中按客户过滤订单。

t1 = (select count(t1) from order where item type = t1), -- missing filter on customerid, 
--so you will get count t1 orders for all customer. Same count for all customers.

您可以修改查询以使用客户过滤器,也可以通过将客户分组来使用具有SUM条件的聚合函数CASE,如下所示-

select customerid,
   firstname,
   lastname,
   SUM(CASE WHEN item_type = 't1' THEN 1 ELSE 0 END) as t1
   SUM(CASE WHEN item_type = 't2' THEN 1 ELSE 0 END) as t2
   SUM(CASE WHEN item_type = 't3' THEN 1 ELSE 0 END) as t3
from order 
   join customer on order.customerid = customer.id
where customer.customertype = 'contractor' 
   and date > dateadd(day,-7,getdate())
Group by customerid, firstname,lastname

答案 1 :(得分:0)

使用#!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk class TableHack(object): # Close the window and quit on delete event. def delete_event(self, widget, event, data=None): gtk.main_quit() return False def __init__(self): # Create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title("Table Hack") self.window.connect("delete_event", self.delete_event) # Create table and fill with text. n = 3 self.table = gtk.Table(n, n, True) for row in range(n): for col in range(n): txt = chr(row * n + col + ord('A')) mrkup = "<span size=\"60000\" weight=\"bold\">" + txt + "</span>" label = gtk.Label() label.set_markup(mrkup) self.table.attach(label, col, col+1, row, row+1) self.window.add(self.table) self.window.show_all() def main(): gtk.main() if __name__ == "__main__": tblHack = TableHack() main() ,您可以尝试以下代码:

PIVOT