SQL Server查询-组合选择语句

时间:2019-01-31 17:23:06

标签: sql sql-server

我觉得我在这里真的很愚蠢。但是尽管进行了3个小时的在线搜索,但我仍然看不到我所缺少的内容。

我有一个MS-SQL发票表,我试图按年份和客户参考对它们进行分组。这是我提出的查询:

SELECT year(INVOICE_DATE)AS YEAR, month (invoice_date)AS MONTH, sum(invoice_net) As invoice_net
FROM            S50INVOICE
--WHERE       ACCOUNT_REF = 'ONLINE' OR Account_ref = 'BADSALES' OR ACCOUNT_REF = 'WEBSALES'
WHERE       ACCOUNT_REF = 'cash'
--WHERE       ACCOUNT_REF <> 'ONLINE' OR Account_ref <> 'BADSALES' OR ACCOUNT_REF <> 'WEBSALES' or ACCOUNT_REF <> 'CASH'
GROUP BY year(invoice_date), month(invoice_date)
order by YEAR, MONTH

现在,我可以每次使用WHERE语句之一运行3次,然后得到三个表的Year / Month / Invoice Net。

但是我希望能够运行一次并使用Year / Invoice / Account_Ref(条件1)/ Account_Ref(条件2)/ Account_Ref(条件3)获得一张表。

我的想法是我应该使用UNION,但是尝试这样做似乎会破坏Group语句,但我仍然只返回3列。

2 个答案:

答案 0 :(得分:1)

是的,这有点棘手,但应该或多或少地适合我的建议。 组没有改变,这完全取决于您基于WHERE条件但基于CASE子句计算组总数的方式。 我无法测试它,因为您的问题没有DDL,但是...请让我知道是否可以:

SELECT 
    year(INVOICE_DATE)AS YEAR, 
    month (invoice_date)AS MONTH, 
    SUM(CASE WHEN ACCOUNT_REF = 'ONLINE' 
           OR Account_ref = 'BADSALES' 
           OR ACCOUNT_REF = 'WEBSALES' 
        THEN invoice_net ELSE 0 END) As invoice_net_Cond1,
    SUM(CASE WHEN ACCOUNT_REF = 'cash' 
        THEN invoice_net ELSE 0 END) As invoice_net_Cond2,
    SUM(CASE WHEN ACCOUNT_REF <> 'ONLINE' 
           OR Account_ref <> 'BADSALES' 
           OR ACCOUNT_REF <> 'WEBSALES' 
           or ACCOUNT_REF <> 'CASH'  
        THEN invoice_net ELSE 0 END) As invoice_net_Cond3
FROM S50INVOICE 
GROUP BY year(invoice_date), month(invoice_date) 
ORDER BY YEAR, MONTH;

答案 1 :(得分:0)

我认为您需要条件聚合:

SELECT year(INVOICE_DATE) AS YEAR, month (invoice_date) AS MONTH, 
       SUM(CASE WHEN ACCOUNT_REF IN ('ONLINE', 'BADSALES' 'WEBSALES' )
                THEN invoice_net ELSE 0
           END) As invoice_net_Cond1,
       SUM(CASE WHEN ACCOUNT_REF = 'cash' THEN invoice_net ELSE 0
           END) As invoice_net_Cond2,
       SUM(CASE WHEN ACCOUNT_REF NOT IN ('ONLINE', 'BADSALES', 'WEBSALES', 'CASH') 
                THEN invoice_net ELSE 0
           END) As invoice_net_Cond3
FROM S50INVOICE 
GROUP BY year(invoice_date), month(invoice_date) 
ORDER BY YEAR, MONTH;