Solved

Nested Query Problem

Posted on 2009-05-05
3
247 Views
Last Modified: 2012-05-06
The nested COUNT query does not recognize a.CustomerID, it comes up asking for that. What am I doing wrong?
INSERT INTO ltblPIFItems(CustomerID, BusinessUnit, ItemID, LastActivity, NumberOfOtherItems, DebtType) 
SELECT a.CustomerID, a.BusinessUnit, a.ItemID, a.LastActivity, b.NumberOfOtherItems, a.DebtType 
FROM ltblAllItems a, (SELECT COUNT(*) - 1 AS NumberOfOtherItems FROM ltblAllItems c WHERE a.CustomerID = c.CustomerID) AS b 
WHERE a.Balance = 0

Open in new window

0
Comment
Question by:bejhan
  • 2
3 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 100 total points
ID: 24309618
change to this:
INSERT INTO ltblPIFItems(CustomerID, BusinessUnit, ItemID, LastActivity, NumberOfOtherItems, DebtType) 
SELECT a.CustomerID, a.BusinessUnit, a.ItemID, a.LastActivity
, (SELECT COUNT(*) - 1 AS NumberOfOtherItems FROM ltblAllItems c WHERE a.CustomerID = c.CustomerID) 
, a.DebtType 
FROM ltblAllItems a
WHERE a.Balance = 0

Open in new window

0
 
LVL 1

Author Comment

by:bejhan
ID: 24309635
Nice I didn't know you could just do that. Thanks!
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 24309654
you could have done like this:
INSERT INTO ltblPIFItems(CustomerID, BusinessUnit, ItemID, LastActivity, NumberOfOtherItems, DebtType) 
SELECT a.CustomerID, a.BusinessUnit, a.ItemID, a.LastActivity
, b.NumberOfOtherItems 
, a.DebtType 
FROM ltblAllItems a
INNER JOIN ( SELECT CustomerID, COUNT(*) - 1 AS NumberOfOtherItems 
              FROM ltblAllItems c 
            GROUP BY CustomerID 
           ) b
  ON (a.CustomerID = c.CustomerID)
WHERE a.Balance = 0

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

As they say in love and is true in SQL: you can sum some Data some of the time, but you can't always aggregate all Data all the time! Introduction: By the end of this Article it is my intention to bring the meaning and value of the above quote to…
This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question