从表构建/创建SQL指标

时间:2019-03-19 21:07:29

标签: sql

我有一张桌子:

SELECT  aaa.sr_nbr,
        aaa.inst_nbr,
        bb.country,
        bb.sr_control_type,
        bb.it_tran_code,
        ccc.cust_name,
        ccc.cust_nbr

FROM tablea1 aaa
INNER JOIN tablea2 bb
ON aaa.inst_id=bb.inst_id AND aaa.item_id=bb.item_id

LEFT JOIN table3 ccc
ON bb.inst_id=ccc.inst_id AND bb.item_id=ccc.item_id
WHERE ccc.cust_name NOT LIKE '%EXP%' 
AND ccc.cust_name NOT LIKE '%RMAA%' mt;

现在,我已经分别创建了指标查询,例如:

SELECT  mt.sr_nbr,
        mt.inst_nbr,
        mt.country,
        mt.sr_control_type,
        mt.it_tran_code,
        mt.cust_name,
        mt.cust_nbr
COUNT(mt.sr_nbr) as cnt_nbr
FROM mt
WHERE mt.it_tran_code <> 'D'
GROUP BY 1,2,3,4,5,6,7;

或另一个:

SELECT  t_2.sr_nbr,
        t_2.inst_nbr,
        t_2.country,
        t_2.sr_control_type,
        t_2.it_tran_code,
        t_2.cust_name,
        t_2.cust_nbr
        SUM(t_2.sn_dup) AS sn_dup_sum
FROM (
    SELECT
    t_1.sr_nbr,
    t_1.inst_nbr,
    t_1.country,
    t_1.sr_control_type,
    t_1.it_tran_code,
    t_1.cust_name,
    t_1.cust_nbr
    COUNT(t_1.sr_nbr) AS sn_dup
FROM
(
    SELECT 
    mt.sr_nbr,
    mt.inst_nbr,
    mt.country,
    mt.sr_control_type,
    mt.it_tran_code,
    mt.cust_name,
    mt.cust_nbr
    FROM mt
WHERE ccc.cust_name NOT LIKE '%EXP%' 
AND ccc.cust_name NOT LIKE '%RMAA%'

) AS t_1
GROUP BY 1,2,3,4,5,6,7
HAVING
COUNT(t_1.sr_nbr) > 1
) AS t_2
GROUP BY 1,2,3,4,5,6,7;

依此类推...我有大约10个类似的指标。

现在,我不知道如何在主表/查询中“放置”那些查询指标的最佳方法。

1 个答案:

答案 0 :(得分:0)

如果能够正确填写INSERT语句,则可以将SELECT查询的结果插入表中。

示例:

INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';

来源:https://www.w3schools.com/sql/sql_insert_into_select.asp

确保结果的数量和类型与您要插入的列匹配。