An interesting SQL problem.

Source: Internet
Author: User
Problem
A friend of mine recently asked me to help solve a problem, the problem description:

There are tables with 3 fields: F1,F2,F3, where 9 digits between 1~9 may appear in each field, and the number of occurrences of 1~9 in the entire table is counted.

Such as:

F1

F2

F3

1

1

2

1

2

3

2

1

2



In the previous example: "1" appeared 4 times, "2" appeared 4 times, "3" appeared 1 times.



The problem, of course, is that you need to use SQL statements as much as possible. Because if you use a program, a variable, an array, and so on, it seems like there is no need to ask this question. When I spent a few minutes of thinking, over, feel the use of SQL to consider the problem, it seems to have a point of view, how to use the most simple and clear ideas and methods to fix this problem? This question and we share, hope to let everyone work, busy, for a change of mood, can exchange a little fun.



Here's how my solution will be published as follows:



SELECT A1, COUNT (A1) as Expr1

From (SELECT A1 from TEST

UNION All

SELECT A2 from TEST

UNION All

SELECT A3 from TEST

)

GROUP by A1


I deliberately set the font color to white, is to avoid interfering with your thinking, if you want to see, you can drag the mouse, select the above blank area, paste the content into WordPad or Query Analyzer can be. The SQL is debugged under SQLSERVER2000.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.