带有内部连接和分组依据的Count(*)

时间:2019-10-01 14:14:34

标签: sql sql-server group-by

我有2张桌子。

我需要从表2中获取具有ID的计数,并从表1中获取ID的名称。

我尝试了以下代码。没用!

import base64
from Crypto.Cipher import AES
from Crypto import Random
import array
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
class AESChiper:

    def __init__(self, key):
        self.bs = 16
        self.key = array.array('B',key).tobytes()

    def encrypt(self, message):
        message = self._pad(message)
        iv = b'0'*16
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(message)).decode('utf-8')


    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]
    @staticmethod
    def keyToBytes(key:str):
        keyLength = len(key)
        bArr = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
        a2 = 0
        b = 30
        c = 2
        while True:
            i = a2 +2
            if  i > keyLength:
                i = keyLength - 1
            i2 = int(a2/2)
            substring = key[a2:i]

            num = int(substring,16)         
            ## convert hex string to decimal 
            ## 8 bits integer in 2's complement
            ## if the value not between -128 - 127 then do substraction
            if num > 127:      
                num = num - 256
            bArr[i2] = num 
            if a2 == b:
                break
            a2 = a2 + c
        return bArr



if __name__ == "__main__":
    key = "7e585aedb1dd597382cf5aaaabfa221d"
    text = 'hello world'
    keyInBytes = AESChiper.keyToBytes(key)
    print(keyInBytes)
    ciphter = AESChiper(keyInBytes)
    ret = ciphter.encrypt(text)
    print(ret)

请尽可能解释我的缺点。

1 个答案:

答案 0 :(得分:3)

在按查询的分组部分进行分组时,需要提及所有列中tat都出现在诸如COUNT之类的集合之外。您在这里缺少ContactName。 固定版本:

select orders.CustomerID, customers.ContactName , count(*) 
from Orders 
left join customers on Customers.CustomerID= Orders.customerid 
group by Orders.customerid, customers.ContactName;

或者,您可以按ID单独分组,然后像这样进行联接:

With OrderCounts AS
(
select orders.CustomerID , count(*)  AS OrderCount
from Orders 
group by Orders.customerid
)
SELECT OrderCounts.CustomerID
, customers.ContactName
, OrderCounts.OrderCount
FROM OrderCounts
left join customers on Customers.CustomerID= OrderCounts.CustomerID 

第一个版本较短且易于键入。在某些情况下,第二个版本的运行速度会更快,因为group by出现在单个表和列上。

第二次给出相同的结果,CustomerID在客户表中必须是唯一的,否则将产生重复项(但如果是这种情况,第一个示例将对订单进行重复计数)。