(另一个)SQL模仿Excel

时间:2014-05-13 03:41:39

标签: sql sql-server sql-server-2005

我已经在这个问题上工作了几天而且似乎无法做到这一点:/ 我会按季度交易金额并加上它们来获得年度总和。然后我计算从今年到最后一年的年度差异。最后,对于每个帐户,我计算其方差为LTE -1GTE 1以及介于-1和1之间的总数。要使用我们的图形软件,我需要将其作为三个不同的记录所有这些都来自单一的复合SELECT陈述。任何意见,将不胜感激。提前谢谢!

这是要作为单行打印的SQL。 Receipts_Total是正整数,YRyear,2012年或2013年。

SELECT 
    Year,
    COUNT(NEGATIVES) AS SUM_OF_NEGATIVES
    , COUNT(POSITIVES) AS SUM_OF_POSITIVES
    , COUNT(FLATS) AS SUM_OF_FLATS
FROM(
    SELECT 
        Year,
        CASE WHEN (Percentage <= -1) THEN 'NEGATIVE' END AS NEGATIVES 
        , CASE WHEN (Percentage >= 1) THEN 'POSITIVE' END AS POSITIVES
        , CASE WHEN ((Percentage > -1) AND (Percentage < 1)) THEN 'FLAT' END AS FLATS
        , CASE WHEN (1 = 1) THEN 4 END AS TOTAL_COUNT
    FROM(
        SELECT 
            '2013' AS Year,
            ((((1.0 * SUM(QR_Dom1.Receipts_Total)) - (1.0 * SUM(QR_Dom.Receipts_Total))) / (1.0 * SUM(QR_Dom.Receipts_Total))) * 100) AS Percentage 

        FROM  QR_Dom INNER JOIN Contacts ON QR_Dom.ID = Contacts.ID INNER JOIN QR_Dom QR_Dom1 ON Contacts.ID = QR_Dom1.ID 

        WHERE ((QR_Dom.YR LIKE '%2012%' AND QR_Dom1.YR LIKE '%2013%')) 

        GROUP BY Contacts.ID, Contacts.COMPANY 

        HAVING (Sum(QR_Dom.Receipts_Total) <> 0 AND Sum(QR_Dom1.Receipts_Total) <> 0)

    ) AS T1

) AS T2
GROUP BY YEAR

示例QR_Dom表:

1111    2012    5000
2222    2012    5000
3333    2012    5000
4444    2012    5000
5555    2012    5000
6666    2012    5000
7777    2012    5000
8888    2012    5000
9999    2012    5000
1212    2012    5000
1111    2013    4000
2222    2013    3000
3333    2013    4999
4444    2013    5001
5555    2013    6000
6666    2013    7000
7777    2013    8000
8888    2013    2000
9999    2013    1000
1212    2013    1500

示例联系人表格:

1111    Nike
2222    Beer
3333    Phone
4444    Car
5555    Yankees
6666    Cat
7777    Cereal
8888    DVD
9999    Toe
1212    Globe

预期产出:

NEGATIVE         2013    5
FLAT             2013    2
POSITIVE         2013    3

1 个答案:

答案 0 :(得分:0)

无法在SQL Server 2005上测试它,但常见的表表达式应​​该稍微简化一下;

WITH cte AS (
  SELECT(b.receipts_total*1.0 - a.receipts_total*1.0) / (a.receipts_total*1.0) * 100 perc
  FROM qr_dom a JOIN qr_dom b ON a.id = b.id AND a.yr = 2012 AND b.yr = 2013
)
SELECT
  2013 AS year,
  SUM(CASE WHEN perc >  1 THEN 1 ELSE 0 END) positive,
  SUM(CASE WHEN perc < -1 THEN 1 ELSE 0 END) negative,
  SUM(CASE WHEN perc <= 1 AND perc >= -1 THEN 1 ELSE 0 END) flat
FROM cte

An SQLfiddle to test with

如果您确实需要单独行中的结果,则可以重写查询以在表单表达式的3个单独查询之间使用UNION ALL